点击使用javascript更改DIV中的文字

时间:2012-01-26 22:29:50

标签: javascript jquery html

我有一个带文字的按钮。单击此按钮后,单击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看起来像是被禁用。

有关tp如何解决此问题的任何想法?

感谢您的时间

ps我也使用jQuery

4 个答案:

答案 0 :(得分:1)

你可以做这样的事情:

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');} 
});

答案 1 :(得分: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 :(得分:0)

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>

答案 3 :(得分:0)

以下是我将如何做到这一点(没有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>