Javascript 获取超链接的 ALT 属性的属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13940976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get an attributes value of the ALT attribute of a hyperlink
提问by Elisabeth
My a-tag (link) contains innerHTML which is an image like this:
我的 a 标签(链接)包含innerHTML,它是这样的图像:
.innerHTML = <img alt="hello world" src="/Content/Images/test.png">
How can I get the text of the altattribute with JQuery?
如何alt使用 JQuery获取属性的文本?
回答by Alexander
Being $ayour <a/>element.
成为$a你的<a/>元素。
Using jQuery you can do:
使用 jQuery,您可以执行以下操作:
$("img", $a).first().attr("alt");
Or, using pure JavaScript:
或者,使用纯 JavaScript:
var $img = $a.getElementsByTagName("img")[0];
console.log($img.alt);
? 看这里。
回答by rlemon
You really don't need jQuery. If you have the a element you can do this:
你真的不需要jQuery。如果你有 a 元素,你可以这样做:
// lets call the anchor tag `link`
var alt = link.getElementsByTagName('img')[0].alt; // assuming a single image tag
Remember attributes map to properties (most), and unless the property is changed, or the attribute, the two should reflect the same data (there are edge cases to this, but they can be handled case-by-case).
记住属性映射到属性(大多数),除非属性或属性发生更改,否则两者应该反映相同的数据(这有边缘情况,但可以逐案处理)。
If you truly do need the attribute there is
如果您确实需要该属性,则有
var alt = link.getElementsByTagName('img')[0].getAttribute('alt');
Last scenario is if you only have the image tag as a string.
最后一种情况是如果您只有图像标签作为字符串。
var str = '<img alt="hello world" src="/Content/Images/test.png">';
var tmp = document.createElement('div');
tmp.innerHTML = str;
var alt = tmp.getElementsByTagName('img')[0].alt;
If you must use jQuery (or just prefer it) then the other answer provided by Alexander and Ashivard will work.
如果您必须使用 jQuery(或只是喜欢它),那么 Alexander 和 Ashivard 提供的其他答案将起作用。
Note: My answer was provided for completeness and more options. I realize the OP asked for jQuery solution and not native js.
注意:我的答案是为了完整性和更多选项而提供的。我意识到 OP 要求使用 jQuery 解决方案而不是本机 js。
回答by Ashirvad
use this.
用这个。
var altName=$('a img').attr('alt');

