编写这个JavaScript的jQuery方式是什么?

时间:2010-12-17 11:10:58

标签: javascript jquery

我不喜欢语法onclick='javascript:doSomething(...

我怎么能用jQuery写这个?

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

3 个答案:

答案 0 :(得分:4)

您将在jQuery中使用事件处理程序/绑定:

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

.click(handler)是一种简短的说法.bind('click', handler)。有关详细信息,请查看event docsThe selector docs应该有助于为您的情况找到合适的选择器。

答案 1 :(得分:0)

在jQuery中,您可以使用click()方法为onclick事件分配函数。

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

    return false;
});

$("#doSomething")引用ID为doSomething

的元素

答案 2 :(得分: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 + 
    "\"); 
});