如何在onclick函数中获取Var?

时间:2014-06-09 17:11:05

标签: javascript jquery

我外面有2个变量。想在onc​​lick事件中显示那两个变量值。无法使用我的下面代码获取值..请帮我解决这个问题。必须在3个小时内解决这个问题。

var myCode = "12345";
var myCount = "5"

$('.cols2.continue').html('<a href="#" onClick="test.element=&#39;myCode, myCount &#39;;test.elemName=+myCode +;">Browse</a>');

现在,我正在使用变量名来代替值。

由于

3 个答案:

答案 0 :(得分:2)

考虑 HTML mangling:

var myCode = function () {
    /* Don't use a string for "code" here either,
       then it can be used as a normal function later on. */
}
var myCount = "5"

var $a = $('<a href="#">Browse</a>')
/* Yay, normal event callback function (and closure)! */ 
$a.click(function () {
    myCode()
    alert(myCount)
})

/* In most cases it's like sufficient just to add the element;
   to replace all content, use .empty().append($a) */
$('.cols2.continue').append($a)

答案 1 :(得分:0)

你的jquery将是

var myCode = "12345";
var myCount = "5"

$('.continue').html('<a href="#" onClick="test.element=&#39;'+myCode+', '+myCount+' &#39;;test.elemName='+myCode+ ';">Browse</a>');

JsFiddel

答案 2 :(得分:0)

试试这个:

var myCode = "12345";
var myCount = "5";

$('.cols2.continue').html('<a href="#" onClick="test.element=&#39;'+myCode+',     '+myCount+'&#39;test.elemName='+myCode +';">Browse</a>');