-1

I have a select-option dropdown with links, both internal and external. I want the external links (and only them) to open in a new tab. This is what I have.

<select id="my-dropdown">
    <option value="">A list of internal and external links</option>
    <option value="http://www.someurl.com">External Link</option>
    <option value="/internal/page">Internal links</option>
</select>

JS to open the links.

<script>
    document.getElementById("my-dropdown").onchange = function() {
        if (this.selectedIndex!==0) {
            window.location.href = this.value;
        }        
    };
</script>

EDIT: Changing the JS to this does it:

<script>
    document.getElementById("my-dropdown").onchange = function() {

        var externalLinkCheck = this.options[this.selectedIndex].value;

        if (this.selectedIndex!==0 && externalLinkCheck.substring(0,4) == "http") {
            window.open(this.value, '_blank');
        } else {
            window.location.href = this.value;
        }        
    };
</script>

chriserwin's answer below is also good! Thanks!

4

2 回答 2

2

You could add another condition that looks for the http:// prefix of the external links.

<script>
    document.getElementById("my-dropdown").onchange = function() {
        if (this.selectedIndex!==0) {
            if (this.value.indexOf('http://') == 0) {
                window.open(this.value);
            }
            else {
                window.location.href = this.value;
            }
        }
    };
</script>

However most browsers have a popup blocker that will close new windows opened programatically. Usually only code that is handling an onclick event will be allowed to bypass the popup blocker.

于 2014-08-27T13:46:07.860 回答
0

你可以这样做:

<script>
   document.getElementById("my-dropdown").onchange = function() {
      if(this.selectedIndex!==0) {
          var win=window.open(this.value, '_blank');
          win.focus();
      }        
   };
</script>
于 2014-08-27T13:43:27.427 回答