避免在每个span元素上写入事件

时间:2019-06-11 12:55:04

标签: javascript jquery

我的脚本正在管理文本,其中单词以跨度分隔,其中将使用一些鼠标事件。有没有一种方法可以使它更优雅,而无需在每个标签上调用事件函数?

<div id="reader">

<span id="2" onmousedown="pushed(this)" onmouseup="released(this)">Hello</span>
<span id="3" onmousedown="pushed(this)" onmouseup="released(this)"> </span>
<span id="4" onmousedown="pushed(this)" onmouseup="released(this)">World</span>
<span id="5" onmousedown="pushed(this)" onmouseup="released(this)"> </span>
<span id="6" onmousedown="pushed(this)" onmouseup="released(this)">of</span>
<span id="7" onmousedown="pushed(this)" onmouseup="released(this)"> </span>
<span id="8" onmousedown="pushed(this)" onmouseup="released(this)">Giants</span>
<span id="9" onmousedown="pushed(this)" onmouseup="released(this)"> </span>

1 个答案:

答案 0 :(得分:0)

$(document).ready(function() {
    $('.buttons-mouse-thing').on('mousedown', function() {
       //DO the magic.
    });

    $('.buttons-mouse-thing').on('onmouseup', function() {
       //DO the magic.
    });
});

或者您可以这样做。如果您的功能相同

$(document).ready(function() {
    $('.buttons-mouse-thing').on('mousedown onmouseup', function() {
       //DO the magic.
    });
});

您的html:

<span id="2" class='buttons-mouse-thing'>Hello</span>
<span id="2" class='buttons-mouse-thing'>Hello</span>
<span id="2" class='buttons-mouse-thing'>Hello</span>
<span id="2" class='buttons-mouse-thing'>Hello</span>
<span id="2" class='buttons-mouse-thing'>Hello</span>
<span id="2" class='buttons-mouse-thing'>Hello</span>
<span id="2" class='buttons-mouse-thing'>Hello</span>

您可以在其文档https://api.jquery.com/中阅读有关jQuery功能on和其他原型的信息