javascript - div parent 和两个 child ,在其他 child 中获取一个 child 的id

标签 javascript jquery html svg

我想在 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/

相关文章:

html - 如何在使用 CSS 加载时将微调器设置到屏幕中间?

javascript - 您传递给 javascript Promise 构造函数的回调的具体术语是什么?

javascript - 获取从日期开始多少天/小时/秒

javascript - Google 脚本数字格式错误

javascript - 水平鼠标滚轮滚动与 Map JQuery 冲突

JavaScript 值传递

javascript - 将多组参数分配给 jQuery 函数

javascript - 在 AngularJS 中准备好文档

javascript - 在 div 中动态插入 React 组件

css - 低分辨率下的 Bootstrap 响应输入宽度