如何在javascript中的onclick函数之外传递这个关键词

时间:2016-06-29 06:08:39

标签: javascript jquery

我需要一个帮助。我在onclick函数中传递this关键字。如果用户需要在不使用onclick事件的情况下调用相同的函数,将如何使用javascript调用它。我正在解释下面的场景。

<input name="optional_0_0_ans" id="optional_0_0_ans" class="form-control firstsec" placeholder="Answer" value="" type="text"> <button type="button" class="btn btn-sm btn-success" style="line-height:12px;" onclick="createNew(this,0,0,1);"><i class="fa fa-plus" aria-hidden="true"></i></button>  

<script>
function createNew(evt,index,childindex,hidevalue){


}
</script>

在上面的代码中,我在onclick事件中传递了this关键字。这里假设用户想要在其他地方调用createNew函数并希望传递相同的this密钥那么它将如何完成。请帮助我。

4 个答案:

答案 0 :(得分:1)

  

这里假设用户想要在其他地方调用createNew函数,并希望传递相同的this关键字然后如何完成。

这是不可能的,因为this只存在内部事件处理程序。处理程序之外不存在“相同this” 我猜你的意思是他们想要传递相同或相似的值。那么this的价值是多少?这是一个DOM元素。他们只需要获取对DOM元素的引用并传递:

var someElement = // get reference to a DOM element
createNew(someElement,0,0,1);

答案 1 :(得分:0)

onclick属性this内部引用当前的DOM元素。因此,如果您想要实现相同的行为,您可以自己简单地获取和解析DOM元素:

var button = document.querySelector('#optional_0_0_ans button');
createNew(button, 0, 0, 3);

答案 2 :(得分:0)

您可以使用以下代码执行此操作:

$(".btn-success").on("click", function(){
    someFunction(this, param1, param2,...)
})

&#34; .btn-success&#34;是一个分配给按钮的类,您要在该按钮上调用JavaScript函数。您也可以在选择器中使用id。

答案 3 :(得分:0)

是的,你可以,为你的元素添加id将更容易处理...

我在你的按钮元素中添加了id来说明

<button type="button" class="btn btn-sm btn-success" id="btn" style="line-height:12px;" onclick="createNew(this,0,0,1);"><i class="fa fa-plus" aria-hidden="true"></i></button>  

<script>
function createNew(evt,index,childindex,hidevalue){    
  alert(evt.type);  //alert button when click
}
createNew(document.getElementById('btn'),4,5,4); //alert button when run
</script>
相关问题