避免使用骨干事件处理程序中的event.preventDefault()样板文件

Pet*_*ons 10 javascript-events backbone.js

我有很多以链接开头的Backbone.js动作

<a href="#makeCookies">Make Cookies</a>
Run Code Online (Sandbox Code Playgroud)

和Backbone.View事件哈希一样

'click [href=#makeCookies]': 'makeCookies'
Run Code Online (Sandbox Code Playgroud)

和一个事件处理函数

makeCookies: function (event) {
    event.preventDefault();
    //code to make cookies
    //I have no intention of ever using #makeCookies in the URL,
    //it's just there so I can wire up the event handler properly
}
Run Code Online (Sandbox Code Playgroud)

是否有一种干净的方法来避免这种样板event.preventDefault().我想过只使用<button>标签而不是<a>标签,但这似乎不合适.

Luk*_*kas 10

如果您计划丢弃它,为什么还需要具有href属性?如何使用类名呢?

HTML代码:

<a class="makeCookies">Make Cookies</a>
Run Code Online (Sandbox Code Playgroud)

查看代码:

'click .makeCookies': 'makeCookies'
...
makeCookies: function (event) {
    // No need for event.preventDefault() anymore!
}
Run Code Online (Sandbox Code Playgroud)

  • 设置`href`等于`javascript:void(0);`.这将为您提供光标并将"a"保持为链接. (3认同)