我在页面上有多个具有不同ID的div标签,其中包含以下属性:。
<div class="alert alert-info" id="1">
<p><b><span class="adName">Name</span></b><br>
<span class="ad1">address1</span><br>
<span class="ad2">address2</span><br>
<span class="ad3">address3</span><br>
<span class="adCity">city</span><br>
<span class="adState">state</span><br>
<span class="adPin">pincode</span><br>
Ph no :<span class="adPhone">phone</span><br>
</p>
</div
我希望在单击特定div时获取span标记内的值。如何识别单击的div然后获取其内容?
答案 0 :(得分:6)
您可以在div的点击事件中使用find()方法。
$('.alert.alert-info').click(function(){
var $this = $(this);
adName = $this.find('.adName').text();
ad2 = $this.find('.ad2').text();
//So you can repeat for remaining elements.
});
答案 1 :(得分:3)
要在单击特定div时获取span标记内的值,请执行以下操作:
$('.alert-info').click(function(){
var $spans = $(this).find('span');
// Loop through all the spans inside this div
$spans.each(function(){
alert($(this).text());
})
});
修改强>
如果我们已经知道.alert-info
是 DIV ,那么就不需要指定从div.alert-info中搜索直接使用.alert-info
来提升表现:))
答案 2 :(得分:3)
这是一个可能的JavaScript解决方案
function getInfo(div) {
var spans = div.getElementsByTagName("span");
return Array.prototype.reduce.call(spans, function(acc, span) {
acc[span.className] = span.textContent;
return acc;
}, {
id: div.id
});
}
var divs = document.getElementsByClassName("alert");
Array.prototype.forEach.call(divs, function(div) {
div.addEventListener("click", function() {
console.log(getInfo(div));
}, false);
});
<div class="alert alert-info" id="1">
<p><b><span class="adName">Name</span></b>
<br> <span class="ad1">address1</span>
<br> <span class="ad2">address2</span>
<br> <span class="ad3">address3</span>
<br> <span class="adCity">city</span>
<br> <span class="adState">state</span>
<br> <span class="adPin">pincode</span>
<br>Ph no :<span class="adPhone">phone</span>
<br>
</p>
</div>
<div class="alert alert-info" id="2">
<p><b><span class="adName">Name</span></b>
<br> <span class="ad1">address1</span>
<br> <span class="ad2">address2</span>
<br> <span class="ad3">address3</span>
<br> <span class="adCity">city</span>
<br> <span class="adState">state</span>
<br> <span class="adPin">pincode</span>
<br>Ph no :<span class="adPhone">phone</span>
<br>
</p>
</div>
答案 3 :(得分:2)
您可以使用jQuery遍历DIV的子元素:
$('.alert-info').click(function(){
alert($(this));//This will give you the clicked DIV object
$(this).find('span'); //This will give you all spans inside it
});
答案 4 :(得分:0)
你可以尝试
$('div.alert-info').click(function(){
var id =$(this).attr("id");
var name = $('#' +id").children("span").text();
});
答案 5 :(得分:0)
如果您想获得跨度的内容 请尝试下面的代码
$('.alert alert-info').click(function()
{
var name = $(this).find('span.adName').html();
var city = $(this).find('span.adCity').html();
// likewise you can get content of all the span under the div which you have clicked
});
答案 6 :(得分:0)
您可以使用this.attributes["id"].value
获取所点击的div的ID名称。