【问题标题】:get parent div id by using image src inside that div using jquery使用 jquery 在该 div 中使用图像 src 获取父 div id
【发布时间】:2017-09-21 17:11:58
【问题描述】:

我有一个父 divdiv_parent 有 4 个 div 元素说 div1div2div3div4 和 1 个按钮 add image

当我点击add image 按钮时,它会在所有 div 中添加 2 张图片。

现在我有 1 张带有 src 的图片,比如 1.png,它位于这 4 个 div 之一中。 所以我的问题是,仅通过 src (1.png) 我怎样才能获得其父 div id?

我试过下面的代码

$('#div_parent > div > img').map(function() {
  if (($(this).attr('src')) == '1.png')
    xx = $(this).attr('id');
  p = xx.parent();
});
alert("--" + xx + "---" + p.attr('id'));

【问题讨论】:

  • 请包含所有相关代码
  • 也许把xx.parent()改成$(this).parent()
  • 附注:您知道p = xx.parent(); 将被执行,即使($(this).attr('src')) == '1.png' 不正确,因为您没有用于 if 子句的花括号?
  • @t.niese mmh 不,事实并非如此。如果没有找到花括号,则在 if - 之后和分号之前找到的第一条语句;是条件为真时执行的操作。因此,如果分号在 if 大括号之后,则不执行任何操作,否则它将运行 if 之后的第一条语句。但是...如果您不使用花括号,则编写要在与 if 相同的行中执行的语句是一种好习惯
  • @FabioLolli 我的观点不是关于if 之后的第一条语句xx = $(this).attr('id'),而是关于p = xx.parent() 之后的语句。除了xx.parent() 在这种情况下没有意义的事实之外,因为xx 是字符串,如果if condition 为假,则查找xx 的父级是没有意义的。看起来更像是 p = xx.parent() 应该与花括号中的 xx = $(this).attr('id') 一起使用。

标签: jquery


【解决方案1】:

还有一种方法可以做到这一点

var id = $('#div_parent').find('img[src="1.png"]') 
   .closest('div')
   .attr('id')

希望这会对你有所帮助。

【讨论】:

  • 非常感谢,它的工作,节省了我很多时间:-)
【解决方案2】:

可以在没有map 的情况下使用Attribute Equals Selectorclosest 来完成。

var id = $('#div_parent > div > img[src="1.png"]') // get the image with the source '1.png'
           .closest('div') // get the closest ancestor with the tag name div
           .attr('id') // get the id of that div

【讨论】:

  • 这对我的问题也有帮助。 :-)
猜你喜欢
  • 2011-10-20
  • 2010-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多