Javascript 使用jquery在同一个类下获取相应的div元素
我有一个主文档div,通过变量Javascript 使用jquery在同一个类下获取相应的div元素,javascript,jquery,html,Javascript,Jquery,Html,我有一个主文档div,通过变量“str” 我有一个功能,可以在str中添加documentDiv任意时间: $('#documentDiv').append(str); 在添加两次之后,我在documentDiv元素中添加了两次相同的结构 <div id='documentDiv'> <div class='customElement'></div><a href='' onclick='append(event);'>append<
“str”
我有一个功能,可以在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>
也许这可以帮助你:
无a标签:
$('.customElement').bind('click',function(){
$(this).append("some text");
});
或使用a标签:
$('.customElement a').bind('click',function(){
$(this).parent().append("some text");
});
我相信你想用这个
function append(event){
$(this).append("some text");
}
由于要动态添加元素,因此应该通过将
on
方法添加到父元素来委派事件
这里有一个例子
函数附加(事件){
$(this.prev().append(“一些文本”);
event.preventdavault();
}
$('documentDiv')。在('click','a',append')代码>
click事件已附加到锚元素。为什么要将click事件绑定到(.customElement)类?我想通过单击任何锚定标记,一些文本将附加到(.customElement)classI下的相应元素中,我不确定您想做什么,但可能更好:$('.customElement a').bind('click',function(){$(this.parent().append(“一些文本”);});
$('.customElement').bind('click',function(){
$(this).append("some text");
});
$('.customElement a').bind('click',function(){
$(this).parent().append("some text");
});
function append(event){
$(this).append("some text");
}