简体   繁体   English

将target =“blank”添加到使用javascript的链接

[英]Adding target=“blank” to links with javascript

I'm attempting to add target="_blank" to links on a page depending on a checkbox click. 我正在尝试将target="_blank"添加到页面上的链接,具体取决于复选框的点击。

On the javascript side I have: 在javascript方面,我有:

 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: 在HTML方面,我有:

<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() . 该页面包含十几个链接,因此我需要复选框以应用于页面上的所有链接 - 为什么我使用了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. 

getElementsByTagName() returns a nodeset. getElementsByTagName()返回一个节点集。 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. 你现在拥有的更像是jQuery语法,它可以在内部为你处理。

This would have shown up in the console. 这将出现在控制台中。 With JS issues, always check the console before wondering what's wrong. 有了JS的问题,在想知道什么是错的之前,请务必检查控制台。

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. 最后,您应该考虑集中处理事件,而不是HTML中指定的内联DOM-zero事件。 Numerous reasons for this that are beyond the scope of this question. 造成这种情况的众多原因超出了本问题的范围。

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

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