jquery 看不到新元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/815074/
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 09:51:25  来源:igfitidea点击:

jquery doesn't see new elements

jquerydomrefresh

提问by Peter

I am new to JQuery, so bear with me :).

我是 JQuery 的新手,所以请耐心等待:)。

I have a simple problem:

我有一个简单的问题:

$(document).ready(function() {

     $("#instrument").change(function() {
         $("#tunings").html("<select id=\"TuningSelector>\"[..]</div>");
     });

     $("#TuningSelector").change(function() {
         DoSomethingWithTheValue();
      }); 

 });

Problem is: When instrument has changed, the script doesn't respond anymore to TuningSelector changes. Like JQuery doesn't see the new TuningSelector element...

问题是:当仪器发生变化时,脚本不再响应 TuningSelector 的变化。就像 JQuery 没有看到新的 TuningSelector 元素......

Do I need to call a refresh on JQuery or so? So that it sees the refreshed DOM?

我需要在 JQuery 上调用刷新吗?以便它看到刷新后的 DOM?

回答by tvanfosson

Generally you want to use onso that it applies the handler to new elements matching the selector and delegate to a higher element in the DOM.

通常,您希望使用on以便它将处理程序应用于与选择器匹配的新元素并委托给 DOM 中的更高元素。

$('body').on( 'change', '#control', function() {
    DoSomething();
});

回答by Sam Hasler

With jQuery events if you want the event to apply to new elements you would use the .livemethod, however jQuery 1.3 doesn't support blur, focus, mouseenter, mouseleave, change, submit events as live events. (change, submit, and blur/focus are on the roadmapfor jQuery 1.4)

对于 jQuery 事件,如果您希望将事件应用于新元素,您可以使用.live方法,但是 jQuery 1.3 不支持模糊、焦点、鼠标输入、鼠标离开、更改、提交事件作为实时事件。(更改、提交和模糊/焦点位于jQuery 1.4的路线图上

As an alternative you could use the liveQueryplugin.

作为替代方案,您可以使用liveQuery插件。