我的问题是我有一个按钮,当用户将鼠标悬停在它上面时,它应该改变文字..当它们悬停时它应该回到之前的状态。
这是我的jQuery
$(document).ready(function() {
$("#followingbutton").hover (
function() {
$(this).replaceWith("<input type='submit' value='Unfollow' id='followingbutton' class='button red' />");
},
function() {
$(this).replaceWith("<input type='submit' value='Following' id='followingbutton' class='button green' />");
});
});
它应该像twitter跟随/取消关注按钮一样。任何人都能为我解释一下吗?
编辑:一切正常,除非它不会“解开”
答案 0 :(得分:2)
为什么不这样(未经测试):
$(document).ready(function() {
$("#followingbutton").hover (
function() {
$(this).val('Unfollow')
.attr('class', 'button red');
},
function() {
$(this).val('Following')
.attr('class', 'button green');
});
});
答案 1 :(得分:1)
它不会被取消,因为当你更换了元素时,事件不再被绑定。
只需更改值和类:
$("#followingbutton").hover (
function() {
$(this).val('Unfollow').toggleClass('red green');
},
function() {
$(this).val('Following').toggleClass('red green');
});
答案 2 :(得分:0)
你为什么不尝试这样做?
$(document).ready(function() {
$("#followingbutton").hover (
function() {
$(this).removeClass('green').addClass('red').attr('value', 'Unfollow');
},
function() {
$(this).removeClass('red').addClass('green').attr('value', 'Follow');
});
});
答案 3 :(得分:0)
这是因为你删除了具有事件监听器的元素,而不是用类似的元素替换它
尝试一下:
$(document).ready(function() {
$("#followingbutton").hover (
function() {
this.value = 'Unfollow';
this.className = 'button red';
},
function() {
this.value = 'Following';
this.className = 'button green';
});
});