简体   繁体   English

Javascript:用标题替换锚点

[英]Javascript: Replace anchor with title

有没有办法使用javascript用标题文本替换锚点中的文本?

 <a href="#" title="3pk Cotton Boxer Shorts (13 - 14 Years)">3pk Cotton Boxer Short...</a>

If you want to do this to all your links, try this: 如果要对所有链接执行此操作,请尝试以下操作:

var link = document.getElementsByTagName('a');
for(var i =0;i<link.length;i++) {
    link[i].innerHTML = link[i].title;
}

​jsFiddle example . jsFiddle示例

Why, of course there is. 为什么,当然有。 Just set the innerHTML property of the anchor equal to the title property. 只需将锚的innerHTML属性设置为与title属性相等即可。

I'm curious, though: why don't you have the correct text in the first place? 不过,我很好奇:为什么您一开始就没有正确的文字?

var links = document.links;

for (var i = 0; i < links.length; i++)
    links[i].innerHTML = links[i].attributes['title'].value;

Use the textContent property: 使用textContent属性:

var anchor_list = document.getElementsByTagName('a'); // or however you'd like to select the target <a>'s
for(var i = 0; i < anchor_list.length; ++i) {
    var a = anchor_list[i];
    if(typeof a.textContent != "undefined") {
        a.textContent = a.title;
    } else {
        a.innerText = a.title; // old IE support
    }
}

innerHTML might not perfrom as expected if you have angle brackets in your title, since it could be parsed as HTML. 如果标题中带有尖括号,则innerHTML可能无法按预期执行,因为它可以解析为HTML。

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

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