【问题标题】:Change text in DIV on click with javascript使用 javascript 单击时更改 DIV 中的文本
【发布时间】:2012-01-28 06:34:29
【问题描述】:

我有一个按钮,里面有文字。单击此按钮时,单击 3 次后它将被禁用(不可单击)。此外,每次单击时按钮文本都必须更改。

查看我的示例(按渲染查看它的工作): http://jsbin.com/univu3/edit#source

现在我想要同样的功能,但需要一个 DIV。这是我到目前为止编写的 javascript 代码:

//Hint
function hint() {
var count = 3

if(count==0) {
        $(this).addClass('disabled');
    };

我的 div:

<div class="ht">HINT (3)</div>

因此,在点击 3 次后,(3) 必须为 (0),并且必须加载“已禁用”类(使 div 看起来像是已禁用。

有什么想法可以解决这个问题吗?

感谢您的宝贵时间

ps 我也用jQuery

【问题讨论】:

  • disabled 属性仅适用于输入元素。
  • 你的例子对我来说很好。究竟是什么问题?

标签: javascript jquery html


【解决方案1】:

又好又短。[更新]

$('.ht').click(function(){
    var $this = $(this);
    var pos = parseInt($this.text().match(/\d+/g)[0]) //use regex to pull the number out;

    if(!pos) return false;

    $this.text($this.text().replace(pos, --pos))

    if(!pos){
        $this.addClass('disabled');
    }
})

http://jsfiddle.net/brentmn/MsQMs/1/

【讨论】:

  • 感谢您的关注。我更新了答案和小提琴。
【解决方案2】:

你可以做这样的事情:

var count=0 
$('.ht').click(function (){    
count++;    
if (count == 1){$('.ht').html('hint 1');}    
if (count == 2) {$('.ht').html('hint 2');}    
if (count == 3) {$('.ht').html('hint 3');
$(.ht).addClass('disabled');} 
});

【讨论】:

    【解决方案3】:
    var hintcount = $('.ht span'),
        availableHint = hintcount.html() | 0;
    
    $('.ht').on('click.threetimes', function() {
       if (availableHint--) {
           hintcount.html(availableHint);
       }
       else {
           $(this).off('click.threetimes').addClass('disabled');
       }
    });
    
    
    
    <div class="ht">HINT (<span>3</span>)</div>
    

    【讨论】:

      【解决方案4】:

      我会这样做(没有 JQuery):

      <!DOCTYPE html>
      <html>
      <head>
      <title></title>
      
      </head>
      <body>
      
      <div id="div">Stop clicking me!</div>
      
      <script>
      
      document.getElementById("div").addEventListener("click", function listener() {
      
          //Get the current 'clicksSoFar' attribute on the div.
          var clicks = +this.getAttribute("clicksSoFar");
      
          //Add to its number of clicks.
          clicks++;
      
          //If it's greater or equal to 3,
          if(clicks >= 3) {
      
              //Gray out the div here (or something) and remove the listener
      
              // --- YOUR CODE HERE ---
      
              this.removeEventListener("click", listener, true);
      
          }
      
          //Set the clicksSoFar attribute to the new number of clicks
          this.setAttribute("clicksSoFar", clicks);
      
      
      }, true);
      
      </script>
      
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-17
        • 2015-04-21
        • 1970-01-01
        • 2023-01-22
        • 1970-01-01
        相关资源
        最近更新 更多