2017-08-15 40 views
0

我的問題如下:如何多次傳遞html對象

我有一個onClick函數。該函數具有當前元素對象和狀態碼的參數。整個函數應該在點擊函數時重新聲明。

的onClick

<button onClick="test(1, this);">test</button> 

功能

function test(status, obj) { 

    if(status == 0) $(obj).attr('onclick','test(1, '+ obj +')'); 
    else if(status == 1) $(obj).attr('onclick','test(0, '+ obj +')'); 
} 

的問題是,第一次點擊後的HTML元素是行不通的。我會得到錯誤信息:

Uncaught SyntaxError: Unexpected identifier 

注意:這只是一個虛擬函數。問題只是關於一般事情。

問題: 爲什麼我不能將參數obj再次傳遞給函數?

該代碼只是一個問題的例子。我知道有幾種解決方案。但我想明白爲什麼它不起作用。

它也不適用於this

+0

_「整個函數應該在點擊函數時重新聲明」_--爲什麼,你究竟想要這樣做? – CBroe

+0

如果您已經在使用jQuery,那麼您應該遠離通過onclick屬性進行事件處理。 – CBroe

+0

我只是想將html obj傳遞給更改後的函數。我想要的是在測試功能中可見的。 – yfain

回答

0

不知道你爲什麼會做這樣的事情,但它可以使用普通的javscript輕鬆實現。

此外,您將實際對象(obj)傳遞給onclick,而您應該只使用「this」,因爲它將在稍後進行評估。

解決方案:

function test(status, obj){ 
 
    alert(status); 
 
    if(status == 0){ 
 
\t obj.setAttribute("onClick", "test(1,this);"); 
 
\t } 
 
\t else if (status == 1){ 
 
\t obj.setAttribute("onClick", "test(0,this);"); 
 
\t } 
 
}
<!DOCTYPE html> 
 
    
 
<html> 
 
    <head> 
 
     <title>Example</title> 
 
     <meta charset="UTF-8"> 
 
     <meta name="viewport" content="width=device-width"> 
 
    </head> 
 
    <body> 
 

 
     <div> 
 
      <button type="button" onclick="test(1,this);" >Click</button> 
 
     </div>  
 
    </body> 
 
</html>

這同樣適用於你的jQuery答案真:

function test(status, obj) { 
 
    alert(status); 
 
    if(status == 0) $(obj).attr('onclick','test(1, this)'); 
 
    else if(status == 1) $(obj).attr('onclick','test(0,this)'); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<!DOCTYPE html> 
 
    
 
<html> 
 
    <head> 
 
     <title>Example</title> 
 
     <meta charset="UTF-8"> 
 
     <meta name="viewport" content="width=device-width"> 
 
    </head> 
 
    <body> 
 
     <div> 
 
      <button type="button" onclick="test(1,this);" >Click</button> 
 
     </div> 
 
    </body> 
 
</html>

+0

謝謝,我明白了。 – yfain

0

你應該用事件處理API,而不是attr的(「的onclick」,...)

function test(status, obj) { 
    if(status == 0) { 
     $(obj).off('click').click(function() { 
      test(1, obj); 
     }); 
    } else if(status == 1) { 
     $(obj).off('click').click(function() { 
      test(0, obj); 
     }); 
    } 
} 
1

你有一個設計問題。而不是將處理程序從一個事件更改爲另一個事件,則應該更改處理程序邏輯。

<button onClick="handler(this)"> 


function handler(obj){ 
    if(!obj.hasOwnProperty('status')) { 
     // this is the first time button got clicked 
     obj.status = 0; // or whatever is the initial value 
    } 
    switch(obj.status){ 
    case 0: // do whatever the 0 case should do 
      obj.status = 1; 
      break; 
    case 1: // do whatever the 1 case should do 
      obj.status = 0; 
      break; 
    } 
}