开发者

Dynamically setting a link's target does nothing

I'm in the process of writing a webpage (in PHP, though this problem does not involve PHP itself) that stores URLs and lets you apply tags to them, thus letting you search for URLs by tags.

I tried to add the capacity to set a checkbox to define whether the URLs will open in new tabs or the same tab by default with a bunch of JavaScript and a cookie. The checkbox properly retains its state between page loadings, but none of the links are ever given target="_blank".

I've given all the URLs the "outbound" class, and am using the slightly undocumented document.getElementsByClassName() function to grab all the links with this class, and I've verified that this part works, as it is returning an array of Links the same size as the number of URLs on the page.

Here's an example of what I'm doing:

function onload() {
    newtab = readCookie("newtab");
    if (newtab == null) {
        createCookie("newtab", "true");
        newtab = "true";
    }
    newtab = (newtab == "true");
    updateLinks(newtab);
}
function updateLinks(newtab) {
    if (newtab)
        target="_blank";
    else
        target="";
    for (link in document.getElementsByClassName("outbound")) {
        link.target = target;
    }
}
function checkboxToggled(checkbox) {
    updateLinks(checkbox.checked);
}

I've verified that 'target' is correctly set in updateLinks() before it loops through all the links. Does anybody have a suggestion as to what could be failing?

I've tested开发者_JAVA百科 this on Google Chrome (my primary browser) and Firefox, and it hasn't worked properly on either. (oddly enough, Firefox gives me a "too much recursion" error)


A couple of issues there, not least that you're not actually setting target on the element at all (you're setting it on a temporary string; details below).

I'd strongly recommend against using for..in on a NodeList, which is what you're doing here:

for (link in document.getElementsByClassName("outbound")) {

for..in loops through all the enumerable properties of an object. (And link will be the property name, not the property value, regardless.) I'd walk it explicitly:

var index, list;
list = document.getElementsByClassName("outbound");
for (index = 0; index < list.length; ++index) {
    link = list[index];
    // ...
}

Also note that getElementsByClassName isn't supported on all browsers.


link in your for in loop doesn't refer to the object, it's just an incrementing value.

  for (link in document.getElementsByClassName("outbound")) {
        document.getElementsByClassName("outbound")[link].target = target;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜