多种结果的一个功能

时间:2016-03-12 16:58:08

标签: javascript html

我已经编写了这个简单的函数来打开一个新窗口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 -->

有没有办法让网址更改取决于我点击的链接,所以我不必为每个链接重写该功能?

谢谢, 斯科特

4 个答案:

答案 0 :(得分:1)

你必须将url作为参数传递给函数

        <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 -->

答案 1 :(得分:1)

您希望将url作为参数传递给函数。

<强> 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);
}

答案 2 :(得分: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);
});

答案 3 :(得分: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>