How can I detect onclick() or similar for individual characters in a text?

前端 未结 6 2129
你的背包
你的背包 2020-12-20 21:49

I\'m new to Javascript and would like to modify a text string by clicking on individual characters. The string is: 0000 0000 0000 0000 representing a binary num

6条回答
  •  执念已碎
    2020-12-20 22:15

    you would need to make each character addressable to the dom (by wrapping it in a span, for example).

    say you've got this HTML

    0000 0000 0000 0000

    you need to

    1. get the nodeValue var $node = $('.binary'), text = $node.text();
    2. trim and explode the binary number text = $.trim(text); var characters = text.split('');
    3. wrap each character in a span text = '' + characters.join('') + '';
    4. inject the wrapped characters $node.html(text);
    5. register a delegated event handler $node.on('click', 'span', function(e){ /* handle */ });

    your handle could look like

    function(e) {
      // abort on empty node
      if (this.innerHTML == ' ') {
        return;
      }
    
      this.innerHTML = this.innerHTML == '1' ? '0' : '1';
    }
    

    putting things together:

    var $node = $('.binary'), 
        text = $.trim($node.text()),
        characters = text.split('');
    
    text = '' + characters.join('') + '';
    $node.html(text).on('click', 'span', function(e) {
        // abort on empty node
        if (this.innerHTML == ' ') {
            return;
        }
    
        this.innerHTML = this.innerHTML == '1' ? '0' : '1';
    });
    

提交回复
热议问题