简体   繁体   English

如何使用事件委托?

[英]How to use event delegation?

I have 2 <span> s loaded from 2 different ajax scripts upon selection from a dropdown box. 从下拉框中选择时,我从2个不同的ajax脚本中加载了2个<span> so my code is something like this 所以我的代码是这样的

<span id='room_rate'>1, 000</span> // loaded by an ajax script
<span id='total_misc'>500</span> // loaded by another ajax script

<input type='text' id='total'/>

<button type='button' id='compute_total'>Compute</button>

Question: 题:

How to use event delegation to get the values from the 2 <span> and display it in the input text total after clicking the compute button ? 在单击compute button后,如何使用事件委托从2个<span>获取值并将其显示在input text total


What I've tried: 我试过的

$(document).ready(function () {
    $(this).on('click', 'span', function () {
        var room_rate = $('#room_rate').val();
        var total_misc = $('#total_misc').val();

        alert(room_rate + total_misc);
    });
});

What I get: 我得到的是:

I don't get the alert and also I dont get an error in the console(F12) 我没有收到警报,也没有在控制台中收到错误消息(F12)

Thank you for your help in advance. 提前谢谢你的帮助。

Read the fine manual... 阅读精美的手册...

.val()

The .val() method is primarily used to get the values of form elements such as input , select and textarea . .val()方法主要用于获取表单元素的值,例如inputselecttextarea

You probably want .text() 你可能想要.text()

I'd also add the delegation to your button, not the spans, ie 我还将代表团添加到您的按钮,而不是跨度,即

$(document).on('click', '#compute_total', function(e) {
    e.preventDefault();

    $('#total').val($('#room_rate').text() + $('#total_misc').text());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM