-1

我正在遍历元素并获取该元素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元素的标签?谢谢!


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

4

3 回答 3

3

您正在尝试在 DOM 对象上调用 find jQuery 函数,使用jQuery对象而不是DOMjavascript 对象来调用 find 。

改变

var noscriptTag = $(this)[0];

var noscriptTag = $(this);

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

于 2013-03-25T10:04:50.220 回答
0

我建议你这样做:

$('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);
});
于 2013-03-25T10:08:22.470 回答
0

尝试这个

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);
});
于 2013-03-25T10:10:27.920 回答