2010-12-17 24 views
1

我不喜歡語法onclick='javascript:doSomething(...什麼是寫這個JavaScript的jQuery方式?

我怎麼能寫這個jQuery?

<a onclick='javascript:doSomething(\"" + 
aName + 
"\",\"" + 
bName + 
"\",\"" + 
aLink + 
"\",\"" + 
aText + 
"\",\"" + 
aUrl + 
"\"); 
return false;' 
href='#'> 
    <img title='Do something' id='doSomethingIcon' src='/images/doSomething.png'> 
</a> 
+1

什麼功能是這個調用? – 2010-12-17 11:14:10

回答

0

在jQuery中你可以使用click()方法來分配功能的onclick事件。

$("#doSomething").click(function(e){ 
    doSomething('"'" + aName + '","' + bName + '","' + aLink + '","' + aText + '","' + aUrl + '"'); 

    return false; 
}); 

$("#doSomething")引用與doSomething

4

的ID你可以使用事件處理程序/綁定jQuery中的元素:

$('a').click(function() { 
    doSomething(/* ... */); 
    return false; // prevent default behaviour (returning false implies 
        // event.preventDefault and event.stopPropagation) 
}); 

.click(handler)是說.bind('click', handler)的一小段路。查看event docs瞭解更多詳情。 The selector docs應該有助於爲您的情況找到合適的選擇器。

+0

返回false並不妨礙元素的正常行爲,因爲你需要使用preventDefault()方法 – yoda 2010-12-17 11:24:16

+0

@yoda:你錯了。 'return false;'意味着'.preventDefault()'和'.stopPropagation()'。請刪除您的downvote。 – jwueller 2010-12-17 11:25:17

+0

對不起@elusive。你也應該解釋一下這個意思,imo。 – yoda 2010-12-17 11:27:19

0

假設你有<a id="testID" href="#"><img...></a>

$('#testID').click(function(e) { 
    e.preventDefault(); // This is same as return; you have. 

    doSomething(\"" + 
     aName + 
     "\",\"" + 
     bName + 
     "\",\"" + 
     aLink + 
     "\",\"" + 
     aText + 
     "\",\"" + 
     aUrl + 
    "\"); 
}); 
+0

這會引發錯誤。 JavaScript區分大小寫。 – jwueller 2010-12-17 11:19:30

+0

您的意思是功能(e)? – Douglas 2010-12-17 11:20:17

+0

謝謝,我解決了我的錯誤。 – raRaRa 2010-12-17 11:20:32

相關問題