簡體   English   中英

在javascript函數中發送此參數

[英]Sending this parameter in javascript function

我有以下復選框:

<label class="checkbox"><input type="checkbox" class="serviceable_check_1" id="serviceable1" name="condition_of_materials[]" onclick="checkOnlyOne(1,obj); return false;" ><span> Serviceable</span></label>

而javascript函數是:

function checkOnlyOne(slno, this) { //Error here 
  console.log(this);
  //$('.serviceable_check_1').not(this).prop('checked', false);
  if(this.checked){
     $('.serviceable_check_1').not(this).prop('checked', false);
  }
}

我收到JavaScript錯誤,原因是Uncaught SyntaxError: Unexpected token this 如何發送此參數onchange事件?

您的這個沒有任何意義。 除非它是DOM的對象或一部分,否則不能將放在函數上。

您可以將this關鍵字放在將觸發函數作為參數的元素上。 然后在函數上,將參數設為chckbx或radiobtn之類的變量(如果這些是您的元素)

document.getElementById('mycheckbox').onchange = myFunction(this);

function myFunction(chckbx){
console.log(chckbx);
}

見下面的片段

 function checkOnlyOne(slno, obj) { //Error here console.log(obj); //$('.serviceable_check_1').not(this).prop('checked', false); if(obj.checked){ $('.serviceable_check_1').not(obj).prop('checked', false); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="checkbox"><input type="checkbox" class="serviceable_check_1" id="serviceable1" name="condition_of_materials[]" onclick="checkOnlyOne(1,this); return false;" ><span> Serviceable</span></label> 

你可以得到事件對象

可維修的

function checkOnlyOne(slno, e {
    console.log(e.target);
    //$('.serviceable_check_1').not(e.target).prop('checked', false);
    if(this.checked)
        $('.serviceable_check_1').not(e.target).prop('checked', false);
}

e.target是您單擊的元素

您應該使用.call並將obj作為第一個參數傳遞,以將其用作this上下文

<input id="serviceable1" onclick="checkOnlyOne.call(obj, 1); return false;" ><span> Serviceable</span></label>

首先要指出的錯誤:您不能命名參數“ this”,因為它是保留字。

現在,“ this”是指其執行上下文,因此,onclick處理程序是該元素的方法,因此將在其上下文(在本例中為input元素)中執行。

注意片段中的第二個警報,您將看到onclick從其主體中調用了您定義的函數,這意味着我們定義的該函數不是輸入對象元素的方法,因此不會“附加”到該對象,並且將從聲明它的上下文(窗口對象)中調用。

 var value = "I'm the value out of the input object"; function displayMessage(context){ //we save the original context as arg alert("input's value: " + context.value); alert("the onclick handler:" + context.onclick); //but notic that the context has changed alert("the context in our function: " + this); alert("when trying without saving the previous context: " + this.value); } 
 <input type="checkbox" id="subscribeToNews" value="Newsletter" onclick="displayMessage(this)"/> <label for="subscribeToNews" >Subscribe </label> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM