2010-12-17 23 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

相关问题