繁体   English   中英

在jQuery中使用.each()定位孩子的孩子

[英]Target child of children with .each() in jQuery

我正在遍历元素,并获取该元素的子元素的src属性。 我有这个HTML代码:

<noscript data-alt="super awesome">
    <img src="http://farm9.staticflickr.com/8235/8585847956_39864361e3.jpg" alt="something" />
</noscript>
<noscript data-alt="super awesome">
    <img src="http://farm9.staticflickr.com/8235/8585847956_39864361e3.jpg" alt="something" />
</noscript>

和jQuery:

$('body').children().each(function() {
  var noscriptTag = $(this)[0];

  var imgAlt = noscriptTag.getAttribute("data-alt");
  var img_src = noscriptTag.find('img');
  var img_regular = img_src.getAttribute("src");
  console.log(img_regular);
});

但我收到此错误:

Uncaught TypeError: Object #<HTMLElement> has no method 'find'

我还尝试了其他各种组合(例如$(this).find('img'); ),但没有使其起作用。

这是演示: http : //jsfiddle.net/LjWhw/

如何定位该元素的img标签? 谢谢!


更新:您不能使用JavaScript定位<noscript>内部的元素。

您正在尝试在DOM对象上调用find jQuery函数,请使用jQuery对象而不是DOM javascript对象对其进行调用。

更改

var noscriptTag = $(this)[0];

var noscriptTag = $(this);

编辑:您还需要相应地更改代码,例如img_src.getAttribute("src"); img_src[0].getAttribute("src"); img_src.attr("src");

我建议您这样做:

$('body').children().each(function() {
  var noscriptTag = $(this).find('noscript').first();
   //---------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----this way
  var imgAlt = noscriptTag.getAttribute("data-alt");
  var img_src = noscriptTag.find('img');
  var img_regular = img_src.attr("src");
  console.log(img_regular);
});

尝试这个

http://jsfiddle.net/UQJsy/1/

$('noscript').each(function () {
    var noscriptTag = $(this);

    var imgAlt = noscriptTag.attr("data-alt");
    var img_src = noscriptTag.children('img');
    var img_regular = img_src.attr("src");
    alert(imgAlt);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM