我想在 jquery 中获取我的 svg 的 id,我尝试了这个 jquery,但它是未定义的。
$(event.target).children('svg').attr("id")
Target.event 返回 p 的数据,当我查看 parent 内部时,我有 mmy 列:
<div class="col-md-4">
<div class="zone" >
<svg id="graphItem0_2" with="300" height="300"></svg>
<p class="glyphicon glyphicon-chevron-down" style="position: absolute; top: 300px; right:20px;" data-toggle="collapse" data-target="#demo2"></p>
</div>
</div>
当我尝试 $(svg).attr("id") 时,我的页面中有很多 svg 元素,我只得到第一个元素,但是当我点击另一个 svg 时,它是相同的 id,然后我的另一个 svg 没有相同的 ID。
最佳答案
您可以将事件点击附加到父 div zone
,然后使用 jQuery 对象 $(this)
搜索 svg:
$('.zone').on('click',function(){
alert( $(this).find('svg').attr("id") );
})
希望这对您有所帮助。
$('.zone').on('click',function(){
alert( $(this).find('svg').attr("id") );
})
.zone{
background-color: red;
}
svg{
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="zone" >
<svg id="graphItem0_2" with="300" height="300"></svg>
<p class="glyphicon glyphicon-chevron-down" style="position: absolute; top: 300px; right:20px;" data-toggle="collapse" data-target="#demo2"></p>
</div>
关于javascript - div parent 和两个 child ,在其他 child 中获取一个 child 的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41483625/