当我点击a
标记我想要调用DoSomething
方法时,我的页面中有两个具有不同ID的html控件。
<div>
<a href="javascript:void(0);" onclick="DoSomething();">
<span id="spnValue" >Value1</span>
</div>
<div>
<a href="javascript:void(0);" onclick="DoSomething();">
<span id="spnValue1">Value2</span>
</div>
function DoSomething() {
var htmlVal = "";
skuList = $("span[id*='spnValue']").html();
}
但无论我点击哪一个都会在htmlVal中显示Value1
。如何区分和检索名为
答案 0 :(得分:5)
您可以将点击的元素对象传递给方法:
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue1">Value2</span>
</div>
然后用它来遍历子span元素:
function DoSomething(obj) {
var htmlVal = "";
skuList = $(obj).find('span').html();
}
<强> Working Demo 强>
答案 1 :(得分:1)
<div>
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue1">Value2</span>
</div>
function DoSomething(obj) {
var htmlVal = "";
skuList = $(obj).parent().find('span').html();
}
答案 2 :(得分:0)
你可以使用你可以找到作为标签上的子元素的span元素来传递函数中的当前元素
<div>
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue" >Value1</span>
</a>
</div>
<div>
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue1">Value2</span>
</a>
</div>
function DoSomething(node) {
var htmlVal = "";
skuList = $(node).find('span').html();//for children
//skuList = $(node).next('span').html();//for siblings
}