为什么我的 jquery .on('change') 不适用于动态添加的选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14942048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:07:49  来源:igfitidea点击:

Why is my jquery .on('change') not working for dynamically added selects

jquery

提问by jaime

I'm adding select elements dynamically, like in the below HTML. I'm not sure why the .on('change' ...) is not working for the dynamic select. What am I missing?

我正在动态添加选择元素,就像下面的 HTML 一样。我不确定为什么 .on('change' ...) 对动态选择不起作用。我错过了什么?

I'm using Chrome 24.0.1312.57 + jquery 1.8.3.

我正在使用 Chrome 24.0.1312.57 + jquery 1.8.3。

<script type="text/javascript">
  $(document).ready(function() {
      $('#x select').on('change', function () { alert('helo'); })
      $('#y select').on('change', function () { alert('helo'); })

      $('#x').html($('#y').html());
  });
</script>

<div id="x"></div>
<div id="y">
    <select>
        <option>O1</option>
        <option>O2</option>
    </select>
</div>

回答by cernunnos

Your code:

您的代码:

$('#x select').on('change', function () { alert('helo'); })

attaches an event handler to the select inside the #x element.

将事件处理程序附加到 #x 元素内的选择。

What you want (from what i understood) is something in the lines of:

你想要的(根据我的理解)是以下几行:

$("#y").on('change','select',function () { alert('helo'); });

This attaches an event handler to the #y element that gets delegated to its children 'select' elements

这将一个事件处理程序附加到 #y 元素,该元素被委派给其子“选择”元素

From http://api.jquery.com/on/

来自http://api.jquery.com/on/

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.

.on() 方法将事件处理程序附加到 jQuery 对象中当前选定的一组元素。

回答by d_ethier

Event binding to elements that are not in the DOM on initial page load will not work. You need to bind to an element further up the DOM that exists to allow the event to trickle down. This is usually the approach that I take:

初始页面加载时对不在 DOM 中的元素的事件绑定将不起作用。您需要绑定到存在于 DOM 之上的元素,以允许事件向下传播。这通常是我采取的方法:

$(document).on({
  change: function() {
    alert('helo');
  }
}, '#x select');

$(document).on({
  change: function() {
    alert('helo');
  }
}, '#y select');

I prefer it as you can add subsequent events easily.

我更喜欢它,因为您可以轻松添加后续事件。

$(document).on({
  change: function() {
    alert('helo');
  },
  blur: function() {
    alert('helo');
  }
}, '#x select');

回答by CodeChimp

Your event binding is set on $(document).ready(). However, if you are dynamically adding them later (like via jQuery.appendTo() or the like), the newly added components need to be binded since they were not part of the inital one that happened in $(document).ready(), which only runs once when the page is loaded and the DOM is initially done.

您的事件绑定设置在 $(document).ready() 上。但是,如果您稍后动态添加它们(例如通过 jQuery.appendTo() 等),则需要绑定新添加的组件,因为它们不是 $(document).ready() 中发生的初始组件的一部分,它只在页面加载和 DOM 最初完成时运行一次。

回答by user889030

Don't use .live()/.bind()/.delegate(), though. You should use .on().

不要使用.live()/ .bind()/ .delegate(),虽然。你应该使用 . on().

for both static and dynamic select changes

对于静态和动态选择更改

$(document).on('change', 'select', function (e) {
    // do something 
});

回答by jamesbat.es

The whole point of .on() is so that you can bind the event to something other than the document. This is what the now depreciated .live() did and it is inefficient in most cases. You are ment to bind the event to the closest parent element that will not be dynamically changed.

.on() 的全部意义在于,您可以将事件绑定到文档以外的其他内容。这就是现在折旧的 .live() 所做的,并且在大多数情况下效率低下。您需要将事件绑定到不会动态更改的最近的父元素。

As far as I am aware this is the correct syntax:

据我所知,这是正确的语法:

$('#x').on('change', 'select', function(){
    alert('hello');
});

If #x or #y will be changed, wrap them on an element and bind the event to that.

如果 #x 或 #y 将被更改,请将它们包装在一个元素上并将事件绑定到该元素。

回答by thecodeparadox

Correct syntax:

正确的语法:

 $('#x').on(
        'change', 
         'select', 
          function () { 
            alert('helo'); 
          }
       );

So syntax of on()for dynamic element seems:

所以on()动态元素的语法似乎是:

$(staticParent).on( eventName, target, handler);

回答by VickenCode

This is easy. Whatever class or id your targeting, try being more precise but no need to include a super parent.

这很简单。无论您的目标是什么类别或 ID,请尝试更精确,但无需包含超级父级。

Example of wrong way:

错误方式示例:

        $('#tablecontent').on('change', '#tablecontent > table.CampaignGrid > tbody > tr > td', function(e) {
            console.log('IN TABLE CONTENT CHANGE');
            var value = e.target.value;
            $('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});

            //alert($(ele[0]).html());
        });

CORRECT WAY:

正确方法:

        $('#tablecontent').on('change', 'table.CampaignGrid > tbody > tr > td', function(e) {
            console.log('IN TABLE CONTENT CHANGE');
            var value = e.target.value;
            $('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});

            //alert($(ele[0]).html());
        });

Notice I dropped the super parent: '#tablecontent'

注意我删除了超级父级:'#tablecontent'

It all about clarity.

这一切都与清晰度有关。

  • V

回答by Dominic

        $('#tablecontent').on('change', '#tablecontent > table.CampaignGrid > tbody > tr > td', function(e) {
            console.log('IN TABLE CONTENT CHANGE');
            var value = e.target.value;
            $('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});

            //alert($(ele[0]).html());
        });

        $('#tablecontent').on('change', '#tablecontent > table.CampaignGrid > tbody > tr > td', function(e) {
            console.log('IN TABLE CONTENT CHANGE');
            var value = e.target.value;
            $('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});

            //alert($(ele[0]).html());
        });

        $('#tablecontent').on('change', 'table.CampaignGrid > tbody > tr > td', function(e) {
            console.log('IN TABLE CONTENT CHANGE');
            var value = e.target.value;
            $('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});

            //alert($(ele[0]).html());
        });

        $('#tablecontent').on('change', '#tablecontent > table.CampaignGrid > tbody > tr > td', function(e) {
            console.log('IN TABLE CONTENT CHANGE');
            var value = e.target.value;
            $('button#updateLuck').prop('disabled', false).css({'color': '#000', 'font-weight': 600});

            //alert($(ele[0]).html());
        });

回答by Dominic

The word in square brackets is the alt text, which gets displayed if the browser can't show the image. Be sure to include meaningful alt text for screen-reading software.

方括号中的单词是替代文本,如果浏览器无法显示图像,则会显示该文本。确保为屏幕阅读软件包含有意义的替代文本。

回答by Naxia

Came across this as I could not get my dynamically created selects which came back from an ajax post with dynamic id's, to trigger the event.

遇到了这个问题,因为我无法从带有动态 ID 的 ajax 帖子返回的动态创建的选择来触发事件。

$(document).on('change', 'select', function (e) {
    $("#theDiv select").on("change",function(){ post("SelectChanged");} );
});

This would not work until I had changed something first so I added

在我先改变一些东西之前这不会起作用所以我添加了

$("#theDiv select").on("change",function(){ post("SelectChanged");} );

However this not meant, that after the change, all other changes then fired twice. This may not be very good practice. But what I did was to to put in a function that is called at the start and each return of ajax.

但这并不意味着,在更改之后,所有其他更改都会触发两次。这可能不是很好的做法。但是我所做的是放入一个在ajax开始和每次返回时调用的函数。

 `function myFuncs(){
    $('#theDiv select').unbind('change');
    $('#theDiv select').on('change' function(){ post('selectChanged'); });
  }`

But had to unbind at start of each function call else it doubled up the functions each time. I am sure there must be a proper way to do this, I just haven't found it yet. Thanks for starting the question.

但是必须在每次函数调用开始时解除绑定,否则每次都会将函数加倍。我确信必须有一种正确的方法来做到这一点,我只是还没有找到。感谢您开始提问。