1

I'm attempting to add target="_blank" to links on a page depending on a checkbox click.

On the javascript side I have:

 function newTab(v) {
      if(v.tab.checked == true) { 
        document.getElementsByTagName('a').setAttribute('target', '_blank');
      } else {
        document.getElementsByTagName('a').setAttribute('target', '_self');
      }
  } //end function

And on the HTML side I have:

<form>
    <input type="checkbox" name="tab" onclick="newTab(this.form)" />
    <label>Open Links In New Tab?</label>
</form>

<a href="//mail.google.com">Gmail</a>

Naturally it isn't as simple as I thought it would be, so it doesn't work.

The page contains over a dozen links so I need the checkbox to apply to all links on the page - why I used getElementsByTagName(). Any help appreciated!

EDIT:

Code that works is as follows:

  function newTab(f) {
    var els = document.getElementsByTagName('a'); //read anchor elements into variable
    if(f.tab.checked == true) { //If the box is checked.
      for (var i in els) {
        els[i].setAttribute('target', '_blank'); //Add 'target="blank"' to the HTML
      } 
    } else { // not checked...
      for (var i in els) {
        els[i].setAttribute('target', '_self'); //Add 'target="self" to HTML
      }
    }
  } //end function. 
4

1 回答 1

4

getElementsByTagName() returns a nodeset. You need to iterate over it and apply the change to each one in turn. What you currently have is more like jQuery syntax, which handles this internally for you.

This would have shown up in the console. With JS issues, always check the console before wondering what's wrong.

var els = document.getElementsByTagName('p');
for (var i=0, len = els.length; i<len; i++)
    els[i].setAttribute('name', 'value');

Also, with checkboxes use change, not click events, as someone might toggle them via the keyboard, not mouse. Lastly, you should look into handling your events centrally, not inline DOM-zero events specified in the HTML. Numerous reasons for this that are beyond the scope of this question.

于 2012-08-13T11:31:09.160 回答