简体   繁体   English

更改纯JavaScript中的href链接

[英]change href link in plain javascript

I'm creating a new DOM element so I can later populate it with data: 我正在创建一个新的DOM元素,以便以后可以用数据填充它:

var bubbleDOM = document.createElement('div');
bubbleDOM.setAttribute('class', 'selection_bubble');
document.body.appendChild(bubbleDOM);

I want to iterate over links in this newly created element to turn addresses like "something.something" into "http://www.something.something". 我想遍历这个新创建的元素中的链接,将“ something.something”之类的地址转换为“ http://www.something.something”。 I don't want jQuery, so I tried this without success: 我不想要jQuery,所以我尝试了一下但没有成功:

var links = bubbleDOM.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    links[i].href = "http://www." + links[i].href.value;
}

Couple of things stand out. 几件事脱颖而出。

  1. links[i].href.value isn't valid. links[i].href.value无效。 Just use links[i].href . 只需使用links[i].href
  2. You should check to make sure the href actually has something in it. 您应该检查以确保href实际上包含某些内容。

Here is an example that works for me: 这是一个对我有用的示例:

var links = bubbleDOM.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    if (!!links[i].href && links[i].href.length > 0) { // Check that there is an href
        links[i].href = "http://www." + links[i].href;
    }
}

links[i].href.value will always be an absolute URL, so if the attribute in HTML looks like links[i].href.value将始终是绝对URL,因此,如果HTML中的属性看起来像

<a href="something.something">

then the value of links[i].href.value will be something like 然后links[i].href.value的值将类似于

"http://current.domain/something.something"

Try using getAttribute('href') instead. 尝试改用getAttribute('href')

use getters and setter to access/modify the attributes : getAttribute and setAttribue . 使用getter和setter访问/修改属性: getAttributesetAttribue

Here's a demo : http://jsfiddle.net/rF9qk/ 这是一个演示: http : //jsfiddle.net/rF9qk/

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

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