使用javascript在单击时更改DIV中的文本
我有一个按钮,里面有文字。单击此按钮时,单击3次后将被禁用(不可单击)。此外,按钮文本必须在每次单击时更改 请参见我的示例(按“渲染”以查看其工作情况): 现在,我想要相同的功能,但需要一个DIV。这是我迄今为止编写的javascript代码:使用javascript在单击时更改DIV中的文本,javascript,jquery,html,Javascript,Jquery,Html,我有一个按钮,里面有文字。单击此按钮时,单击3次后将被禁用(不可单击)。此外,按钮文本必须在每次单击时更改 请参见我的示例(按“渲染”以查看其工作情况): 现在,我想要相同的功能,但需要一个DIV。这是我迄今为止编写的javascript代码: //Hint function hint() { var count = 3 if(count==0) { $(this).addClass('disabled'); }; 我的部门: <div class="ht"&
//Hint
function hint() {
var count = 3
if(count==0) {
$(this).addClass('disabled');
};
我的部门:
<div class="ht">HINT (3)</div>
提示(3)
因此,在单击3次之后,(3)必须是(0),并且必须加载类“disabled”(使div看起来像是被禁用的)
你知道怎么做吗
谢谢你抽出时间
ps我也使用jQuery您可以这样做:
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');}
});
var hintcount=$('.ht span'),
availableHint=hintcount.html()| 0;
$('.ht')。on('click.threetimes',function(){
如果(可用提示--){
html(可获得的链接);
}
否则{
$(this).off('click.threetimes').addClass('disabled');
}
});
提示(3)
以下是我的做法(无JQuery):
别点击我!
document.getElementById(“div”).addEventListener(“单击”,函数侦听器(){
//获取div上当前的“clicksSoFar”属性。
var clicks=+this.getAttribute(“clicksFar”);
//增加点击次数。
点击++;
//如果大于或等于3,
如果(单击次数>=3){
//在这里(或其他地方)灰显div并删除侦听器
//---你的代码在这里---
this.removeEventListener(“单击”,listener,true);
}
//将ClicksFar属性设置为新的单击次数
此.setAttribute(“clicksSoFar”,clicks);
},对);
又漂亮又短。[更新]
$('.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');
}
})
禁用属性仅适用于输入元素。您的示例对我来说很好。问题到底是什么?感谢您的关注。我更新了答案和小提琴。
<!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>
$('.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');
}
})