我有一些具有相似内容和链接,图像等的div请求扩展的jQuery函数.
div具有唯一的id,但它们的内容具有相似的字段和结构.
例如,HTML是:
<div id="bar1">
<some xhtml><input type="textbox" class="searchTxt" />
<some xhtml><img class="notify" src="blank.gif" />
</div>
<div id="bar2">
<some xhtml><input type="textbox" class="searchTxt" />
<some xhtml><img class="notify" src="blank.gif" />
...
Run Code Online (Sandbox Code Playgroud)
和jQuery:
$('.searchTxt').click(function(obj) {
//now here I want to know which searchTxt that was clicked,
//so I can change the img-source..
//without parent().parent() that may fail since div-content may vary.
});
Run Code Online (Sandbox Code Playgroud)
编辑:
这部分是一个糟糕的例子,因为jQuery不会修改任何内容,而且这总是可用的.
想象一下两个div中的图像应该被click-function隐藏.
示例已更新.
什么是正确的道路?
您可以使用closest()选择器:
Run Code Online (Sandbox Code Playgroud)$('.searchTxt').click(function(obj) { alert($(this).closest("div[id^='bar']").prop("id")); });
或者,您可以将事件处理程序添加到<div>元素并允许事件传播到它. event.target会引用文本元素并this引用div:
Run Code Online (Sandbox Code Playgroud)$('div[id^="bar"]').click(function (evt) { if (evt.target.className == "searchTxt") alert(this.id); });
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |