jQuery尝试通过onclick事件使用动态ID [英] Jquery trying to work with dynamic id's with onclick event
问题描述
我遇到的问题是,当我单击LIKE div时,它会打开所有文本框
The problem I'm having is that when I click on the LIKE div it opens all textboxes
在点击事件上只需要显示一个文本框即可.
It needs to display only the one textbox on the click event.
以下是示例html:
<div id="sublike-1">Like</div>
<div id="sublike-form-1"><input type="text" /> Save</div>
<div id="sublike-2">Like</div>
<div id="sublike-form-2"><input type="text" /> Save</div>
<div id="sublike-3">Like</div>
<div id="sublike-form-3"><input type="text" /> Save</div>
我的Jquery:
// Display Sub Like form
$(this).find("div[id^='sublike-']").live('click', function(){
$("div").find("div[id^='sublike-form-']").toggle();
});
我该怎么做,以使其不会同时打开两个文本框,我必须更改html div,jquery还是两者都更改?
What can I do so that it does not open both textboxes at the same time, must I change my html div's, my jquery or both?
谢谢
推荐答案
如果您完全确定每个文本框都将在"Like"元素旁边,则可以使用 next
:
If you're absolutely sure that every textbox will be next to the "Like" element, you can use siblings
or next
:
$(document).find("div[id^='sublike-']").live('click', function(){
$(this).siblings("[id^='sublike-form-']:first").toggle();
});
但是,如果文本框可能距离Like元素很远",则可以解析id:
But if textbox might be "far" from the Like element, you can parse the id:
$(document).find("div[id^='sublike-']").live('click', function(){
var num = this.id.split('-')[1];
$('#sublike-form-' + num).toggle();
});
检查以下示例: http://jsfiddle.net/marcosfromero/ZbTzN/
这篇关于jQuery尝试通过onclick事件使用动态ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!