2016-03-12 84 views
-4

我已經寫了這個簡單的函數來打開一個新窗口onclick;多種結果的一種功能

<script type="text/javascript"> 
function solopopup() 
{ 
mywindow = window.open("http://www.sample.com/solopopup","mywindow","menubar=1,resizable=1,width=768,height=850"); 
mywindow.moveTo(0, 0); 
} 
</script> 

<a href="#" onclick="solopopup()"><li>one</li></a> <!--This goes to url above --> 
<a href="#" onclick="solopopup()"><li>Two</li></a> <!--This goes to a different url --> 

有沒有一種方法可以使URL更改取決於我點擊的鏈接,所以我不必爲每個鏈接重寫函數?

感謝, 斯科特

+0

將URL傳遞作爲參數傳遞給函數。 –

+0

這是一個非常鈍的論點,而且你的論點是你「你是如何提出你的問題的」這一事實使我想在刪除它之前知道原始問題。 –

回答

1

您必須將網址作爲參數傳遞給函數

 <script type="text/javascript"> 
     function solopopup(url) 
     { 
     mywindow = window.open(url,"mywindow","menubar=1,resizable=1,width=768,height=850"); 
     mywindow.moveTo(0, 0); 
     } 

     <a href="#" onclick="solopopup('http://www.sample.com/solopopup')"><li>one</li></a> <!--This goes to url above --> 
     <a href="#" onclick="solopopup('http://www.sample.com/solopopup')"><li>Two</li></a> <!--This goes to a different url --> 
+0

代碼轉儲不是*有用*的答案。說你改變了什麼,爲什麼。另外,請記住那些引號。點擊上面的任一鏈接都會給你一個JavaScript錯誤。 –

1

你要的網址傳遞給函數作爲參數。

HTML

<a href="#" onclick="solopopup('http://www.mysite1.com')"><li>one</li></a> 
<a href="#" onclick="solopopup('http://www.mysite2.com')"><li>Two</li></a> 

的JavaScript

function solopopup(url) 
{ 
    mywindow = window.open(url,"mywindow","menubar=1,resizable=1,width=768,height=850"); 
    mywindow.moveTo(0, 0); 
} 
0

您的鏈接頃突兀,因爲如果JS是禁用的,他們將無法正常工作。更好地利用

function mylinkHandler() { 
 
    var mywindow = window.open(this.href, "mywindow", "menubar=1,resizable=1,width=768,height=850"); 
 
    mywindow.moveTo(0, 0); 
 
} 
 
[].forEach.call(document.querySelectorAll('.mylink'), function(el) { 
 
    el.addEventListener('click', mylinkHandler); 
 
});
<ul> 
 
    <li><a class="mylink" href="http://www.example.com/one">one</a></li> 
 
    <li><a class="mylink" href="http://www.example.com/two">two</a></li> 
 
</ul>

1

移動JS出了錨和使用數據屬性來存儲的URL。

HTML

<a class="url" data-url="http://one.com"> 
    <li>one</li> 
</a> 

<a class="url" data-url="http://two.com"> 
    <li>Two</li> 
</a> 

JS

function solopopup(e) { 
    e.preventDefault(); 
    mywindow = window.open(this.dataset.url, "mywindow", "menubar=1,resizable=1,width=768,height=850"); 
    mywindow.moveTo(0, 0); 
} 

var urls = document.querySelectorAll('.url'); 

[].slice.call(urls).forEach(function (a) { 
    a.addEventListener('click', solopopup, false); 
}); 
+0

已投票,因爲與其他人不同,此答案包含event.preventDefault()。 – Roberto