在onclick函数中返回变量

时间:2016-05-28 14:45:50

标签: javascript jquery variables url

我有一个javascript代码,它返回一个名为foo

的变量

我需要将此变量作为文本传递给onclick函数

function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

var foo = getQueryVariable("dv1");
<ul class="answer-list">
	<li><a class="btn rollover" onclick="nextQuestion(6, 'http://www.example.net/iclk/redirect.php?apxcode=042004&id=eT9HmN9XD3xMgT8nKUj0KRjMIWuXeTj0KN2-0N&dv1=FOOHERE');"><span>Yes</span></a></li>
	<li><a class="btn rollover" onclick="nextQuestion(6, 'http://www.example.net/iclk/redirect.php?apxcode=042004&id=eT9HmN9XD3xMgT8nKUj0KRjMIWuXeTj0KN2-0N&dv1=FOOHERE');"><span>No</span></a></li>
</ul>

我需要知道如何将变量foo传递到onclick函数链接,代替 FOOHERE

如何做才能获得正确的链接?

2 个答案:

答案 0 :(得分:1)

您可以使用两个参数调用另一个函数,另一个函数将调用nextQuestion

<强> HTML:

<ul class="answer-list">
    <li><a class="btn rollover" onclick="someFunc(6, 'http://www.example.net/iclk/redirect.php?apxcode=042004&id=eT9HmN9XD3xMgT8nKUj0KRjMIWuXeTj0KN2-0N&dv1=');"><span>Yes</span></a></li>
    <li><a class="btn rollover" onclick="someFunc(6, 'http://www.example.net/iclk/redirect.php?apxcode=042004&id=eT9HmN9XD3xMgT8nKUj0KRjMIWuXeTj0KN2-0N&dv1=');"><span>No</span></a></li>
</ul>

<强>使用Javascript:

function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

function someFunc(number, link) {
    link = link + getQueryVariable("dv1");
    nextQuestion(number, link )
}

答案 1 :(得分:1)

您可以使用此简单代码

&#13;
&#13;
function nextQuestion(num, link){
    var val = link.replace(/.*&dv1=/, "");
    console.log(val);
}
&#13;
<a onclick="nextQuestion(6, 'http://www.example.net/iclk/redirect.php?apxcode=042004&id=eT9HmN9XD3xMgT8nKUj0KRjMIWuXeTj0KN2-0N&dv1=FOOHERE1');">Yes</a>
<a onclick="nextQuestion(6, 'http://www.example.net/iclk/redirect.php?apxcode=042004&id=eT9HmN9XD3xMgT8nKUj0KRjMIWuXeTj0KN2-0N&dv1=FOOHERE2');">No</a>
&#13;
&#13;
&#13;