简体   繁体   English

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

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

I'm iterating through the elements and grabbing the src attribute of the child of that element. 我正在遍历元素,并获取该元素的子元素的src属性。 I have this HTML code: 我有这个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>

and jQuery: 和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);
});

But I'm getting this error: 但我收到此错误:

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

I also tried various other combinations (like $(this).find('img'); ) without making it work. 我还尝试了其他各种组合(例如$(this).find('img'); ),但没有使其起作用。

Here's the demo: http://jsfiddle.net/LjWhw/ 这是演示: http : //jsfiddle.net/LjWhw/

How do I target the img tag of that element? 如何定位该元素的img标签? Thanks! 谢谢!


UPDATE: You can't target elements which are inside <noscript> with JavaScript. 更新:您不能使用JavaScript定位<noscript>内部的元素。

You are trying to call find jQuery function on DOM object, Use jQuery object instead of DOM javascript object to call find on it. 您正在尝试在DOM对象上调用find jQuery函数,请使用jQuery对象而不是DOM javascript对象对其进行调用。

Change 更改

var noscriptTag = $(this)[0];

To

var noscriptTag = $(this);

Edit: You will also need to change the code accordingly eg img_src.getAttribute("src"); 编辑:您还需要相应地更改代码,例如img_src.getAttribute("src"); to img_src[0].getAttribute("src"); img_src[0].getAttribute("src"); or img_src.attr("src"); img_src.attr("src");

I would suggest you to do it this way: 我建议您这样做:

$('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);
});

try this 尝试这个

http://jsfiddle.net/UQJsy/1/ 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