简体   繁体   English

如何获取使用jQuery附加的单击时超链接的ID

[英]How to get Id of hyperlink on click which was appended using jquery

I am appendend a hyperlink to the html page using append() method, It is a list of hyperlinks, and I get all other elements id by this.id, but am not able for the appended row, why this happening? 我使用append()方法将超链接附加到html页面,这是超链接的列表,并且我通过this.id获取所有其他元素id,但无法添加行,为什么会这样? is there any other way to append ?? 还有其他方法可以附加吗?

thanks in advance 提前致谢

It sounds like somewhere in your code you have this: 听起来在代码中的某处您有以下内容:

$("selector for links").on("click", function() {
    // Using this.id here
    return false; // Since they're links I assume you do this or e.preventDefault();
});

and after that code runs, you add another link, but clicking it doesn't trigger the handler above. 在该代码运行之后,您添加了另一个链接,但是单击它不会触发上面的处理程序。 That's because the code above hooks the event on the elements that exist as of when it runs; 这是因为上面的代码将事件挂接到运行时已存在的元素上。 since the link you add didn't exist, its click event didn't get hooked. 由于您添加的链接不存在,因此不会钩住其点击事件。

You can use event delegation to solve this, by changing the code above to: 您可以使用事件委托来解决此问题,方法是将上面的代码更改为:

$("selector for container").on("click", "selector for links", function() {
    // Using this.id here
    return false;
});

That hooks click on a container that holds the links, but fires the handler as though the event had been hooked on individual links. 该钩子单击包含链接的容器 ,但是触发该处理程序,就好像该事件已被钩在单个链接上一样。 So since the event is hooked on the container, you get the event even when you add new links. 因此,由于该事件已挂接到容器上,因此即使添加新链接也可以获取该事件。

Concrete example: 具体示例:

$(document).on("click", "a", function() {
    alert(this.id);
    return false;
});

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

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