动态更改js函数内的onclick引用

时间:2017-09-08 09:26:29

标签: javascript dynamic

<html>
<script>
function fn1(event)
{

alert("in fn1"+event.id);
}

function fn2(event)
{

alert(event.id);
}

function fnChange(event)
{
 alert(event.id +"  "+event.name);
 event.onclick=fn1;
//without passing parameter ,the code works.I dono how to change the reference to fn1 along with the variable passed
 

}
</script>
<body>
<button id="b1" name="b1Name" onclick="fnChange(this);">The time is?</button>


</body>

</html>

我想在调用fnChange之后,每次点击该按钮都应该调用fn1以及作为参数传递的buttonReference。

谢谢和问候, 湿婆RV

2 个答案:

答案 0 :(得分:0)

只需使用闭包(例如布尔firstClickDone)来检测是否已完成第一次点击

<html>
<script>

var firstClickDone = false;

function fn1(event)
{

alert("in fn1"+event.id);
}

function fn2(event)
{

alert(event.id);
}

function fnChange(event)
{

 if(firstClickDone){
   fn1(event);
 }
 else{
   alert(event.id +"  "+event.name);
   firstClickDone = true;
 }

}
</script>
<body>
<button id="b1" name="b1Name" onclick="fnChange(this);">The time is?</button>


</body>

</html>

答案 1 :(得分:0)

下面是示例代码,您可以将事件ID存储在变量中并传递参数以获取事件的值:

&#13;
&#13;
<script>
function fn1(event)
{

alert("in fn1"+event);
}

function fn2(event)
{

alert(event.id);
}

function fnChange(event)
{
 alert(event.id +"  "+event.name);
 var temp=(event.id +"  "+event.name);
fn1(temp);
//without passing parameter ,the code works.I dono how to change the reference to fn1 along with the variable passed
 

}
</script>
<body>
<button id="b1" name="b1Name" onclick="fnChange(this);">The time is?</button>


</body>
&#13;
&#13;
&#13;