使锚点成为href的一部分?

Liu*_*ang 8 html javascript anchor http href

我有一个看起来像这样的链接:

<a class="link" href="https://www.google.com/?q=">Hello world</a>
Run Code Online (Sandbox Code Playgroud)

是否有可能将其呈现为Hello World

该链接应指向https://www.google.com/?q=Hello world,而不在href中指定此链接.

我在想javascript可能是最好的方法吗?

任何帮助都会很好!

Sud*_*oti 6

假设你的href格式总是如此https://www.google.com/?q=,你可以这样做:

var eles = document.getElementsByTagName('a');
for(var i = 0, len = eles.length; i < len; i++) {
    //get the inner html of anchor tag
    //var text = eles[i].innerHTML;
    //better use textContent
    var text = eles[i].textContent;
    //append anchor tag inner html to href
    eles[i].href += text;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你想/需要支持IE8(urgh),`eles [i] .textContent || eles [i] .innerText || ""' (3认同)

Kri*_*h R 2

你能试试这个吗

<a class="link" href="https://www.google.com/?q=" onclick='window.location.href = this.href+encodeURI(this.textContent); return false; '>Hello world</a>
Run Code Online (Sandbox Code Playgroud)

添加了onclick事件处理程序并获取标签的hreftextContent并将它们组合在一起。然后它会给出预期的结果。

更新: 如果您的页面中有很多链接,那么您可以创建 javascript 函数并在必要时调用它。

JavaScript:

 function Search(d){
     window.location.href = d.href+encodeURI(d.textContent); 
    return false; 
 }
Run Code Online (Sandbox Code Playgroud)

HTML:

 <a class="link" href="https://www.google.com/?q=" onclick='Search(this);'>Hello world</a>
Run Code Online (Sandbox Code Playgroud)

即使您觉得集成 jquery,该过程也可能会变得更简单。