gpt4 book ai didi

javascript - 使用jquery获取同一类下的相应div元素

转载 作者:行者123 更新时间:2023-11-30 12:07:29 25 4
gpt4 key购买 nike

我有一个主文档 div,通过变量 "str" 添加一些 html 元素

<div id='documentDiv'></div>

我有一个功能,可以将一些 html 元素添加到我的 #documentDiv

var str="<div class='customElement'></div><a href='' onclick='append(event);'>append</a>"

而且我有一个功能,可以根据需要多次将 str 附加到 documentDiv:

 $('#documentDiv').append(str);

添加两次后,我在 documentDiv 元素中添加了两次相同的结构

<div id='documentDiv'>
<div class='customElement'></div><a href='' onclick='append(event);'>append</a> // want to append some text to respective .customElement div
<div class='customElement'></div><a href='' onclick='append(event);'>append</a>
</div>

我的问题是 onclick ,我想在 customElement 类下的 respective div 中添加一些东西。但是对于 onClick , 它总是附加到第一个 div。我如何使用 jquery 获取相应的 div 元素?

function append(event){
$('.customElement').append("some text");
}

最佳答案

也许这可以帮助你:没有标签:

$('.customElement').bind('click',function(){
$(this).append("some text");
});

或使用 a 标签:

$('.customElement a').bind('click',function(){
$(this).parent().append("some text");
});

关于javascript - 使用jquery获取同一类下的相应div元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34770458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com