简体   繁体   English

无法检测到已更改的ID

[英]Can't detect changed id

When I change the id of a button I cannot find the new id with on.("click"). 当我更改按钮的ID时,我找不到新的id。(“click”)。 The function console.log() does detect that it's changed but I cannot detect it with the on() function. 函数console.log()确实检测到它已被更改但我无法使用on()函数检测到它。

HTML: HTML:

<form id="formName" action="" method="post">
    <input type="submit" id="submitBtn" value="Submit" />
</form>
<button id="change">Change</button>

JS: JS:

$("#change").on("click", function(){
    $("#submitBtn").attr("id", "NewBtn"); 
});

$("#formName").submit(function(e){
    e.preventDefault();
});

$("#NewBtn").on("click", function(){
    alert("Hello"); 
});

So I need it to alert "Hello" after I have clicked on change. 所以我在点击更改后需要它提醒“你好”。 It does change the id I checked that with inspect element. 它确实改变了我用inspect元素检查的id。

Fiddle: http://jsfiddle.net/WvbXX/ 小提琴: http//jsfiddle.net/WvbXX/

Change 更改

$("#NewBtn").on("click", function(){

to

$(document).on("click", "#NewBtn", function(){

The reason for this is that you're wanting to use the delegate form of .on() . 原因是你想要使用.on()委托形式。 This call is a little different in that it takes a "string" as the second parameter. 这个调用有点不同,因为它需要一个“字符串”作为第二个参数。 That string is the selector for your "dynamic" element while the main selector need either be a parent container (not created dynamically) or the document itself. 该字符串是“动态”元素的选择器,而主选择器需要是父容器(不是动态创建的)或document本身。

jsFiddle 的jsfiddle

you are setting onclick event for newBtn on load of page for the first time but unfortunately newBtn not available that time. 您是第一次在页面加载时为newBtn设置onclick事件,但不幸的是newBtn当时不可用。 hence after changing the id it will not trigger onclick function for newBtn. 因此在更改id后,它不会触发newBtn的onclick函数。

you can do one thing to make it work, set onclick event for newBtn inside the same function where you are changing the id like below. 你可以做一件事让它工作,在你正在改变id的同一个函数中为newBtn设置onclick事件,如下所示。

$("#change").on("click", function(){
    $("#submitBtn").attr("id", "NewBtn"); 
    // set on click event for new button
    $("#NewBtn").on("click", function(){
    alert("Hello"); 
});
});

.attr() function does not have a callback and thus it cannot be checked unless you setup an interval using setInterval but the function itself executes pretty soon so you are not going to need it. .attr()函数没有回调,因此除非你使用setInterval设置一个间隔但是函数本身很快就会执行所以你不需要它,所以它不能被检查。

For solving the problem in hand event delegation proposed by tymeJV is the right way to do it. 为了解决手中的问题,tymeJV提出的事件委托是正确的方法。

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

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