[英]jquery attr() method doesn't work but javascript version does
Here is my current javascript code 这是我当前的JavaScript代码
var image = iframe.contentWindow.document.getElementsByClassName('productVisu').getElementsByTagName('img').getAttribute('src');
This works in retrieving the URL attribute of an image. 这可用于检索图像的URL属性。 However when I try this jquery version:
但是,当我尝试这个jQuery版本:
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var image = $('iframe').contents().find('.productVisu').$('img').attr('src');
I get the firefox error that this not a function. 我得到的不是这个功能的Firefox错误。 How do I resolve this issue and get the jquery version working?
如何解决此问题并使jquery版本正常工作?
Thanks 谢谢
Change this: 更改此:
$('iframe').contents().find('.productVisu').$('img').attr('src');
to: 至:
$('iframe').contents().find('.productVisu img').attr('src');
I'm not sure how your original code works, since getElementsByClassName
and getElementsByTagName
return node lists, not individual nodes. 我不确定原始代码的工作方式,因为
getElementsByClassName
和getElementsByTagName
返回节点列表,而不是单个节点。
Try this instead: 尝试以下方法:
var image = iframe.contentDocument.querySelector(".productVisu img").src;
Never use jQuery when you can use Vanilla JS . 可以使用Vanilla JS时,切勿使用jQuery。 It's like turning a screw with a sledgehammer.
就像用大锤转动螺丝一样。
I don't understand the need for the first two lines of code in your example. 我不理解您的示例中前两行代码的必要性。 You could easily do this:
您可以轻松地做到这一点:
var image = $('iframe').eq(0).find('.productVisu img').attr('src');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.