如何检测文本中单个字符的onclick()或类似内容?

foo*_*foo 5 javascript string onclick

我是Javascript的新手,想通过点击单个字符来修改文本字符串.字符串是:0000 0000 0000 0000表示二进制数.我希望能够通过直接单击文本来切换0到a 1.

我试图使用onclick(),但只设法检测整个段落的点击.检测哪个字符被点击的适当方法是什么?

T.J*_*der 4

对于如此少量的字符,最简单的方法是将它们放在自己的范围内:

<span>0</span><span>0</span><span>0</span><span>0</span> <span>0</span><span>0</span><span>0</span><span>0</span> <span>0</span><span>0</span><span>0</span><span>0</span>
Run Code Online (Sandbox Code Playgroud)

我还将所有这些放入一个容器中,并将click事件挂接到容器上而不是单个跨度上,因此:

<div id="container">
    <span>0</span><span>0</span><span>0</span><span>0</span> <span>0</span><span>0</span><span>0</span><span>0</span> <span>0</span><span>0</span><span>0</span><span>0</span>
</div>
Run Code Online (Sandbox Code Playgroud)

然后把它挂起来:

var container = document.getElementById("container");
if (container.addEventListener) {
    container.addEventListener('click', clickHandler, false);
}
else if (container.attachEvent) {
    container.attachEvent('onclick', function(e) {
        return clickHandler.call(container, e || window.event);
    });
}
Run Code Online (Sandbox Code Playgroud)

在您的单击处理程序中,用于event.target找出单击了哪个范围:

function clickHandler(event) {
    var span = event.target;
    // Do something with the span, such as look at its `innerHTML` and
    // see if it's "0" -- if so, make it "1"; if not, make it "0"
}
Run Code Online (Sandbox Code Playgroud)

更多探索:


正如您在上面所看到的,我必须解决一些浏览器使用标准addEventListener,而其他浏览器(IE8 及更早版本)使用attachEvent. 我建议使用好的 JavaScript 库,如jQueryPrototypeYUIClosure其他库。它们为您解决了这些类型的浏览器不一致问题,并添加了许多非常有用的实用功能,以便您可以专注于您想要做的事情。

例如,使用 jQuery 编写的处理程序代码:

$("#container").on("click", "span", function() {
    // `this` refers to the span that was clicked; you can use
    // `innerHTML` as above, or wrap it in a jQuery instance
    // like this:
    //    var $this = $(this);
    // ...and then use jQuery's `html` function to both
    // retrieve and set the HTML.
});
Run Code Online (Sandbox Code Playgroud)