Please take a look at this fiddle
有人请告诉我如何在单击按钮#edit_mode
时为表格单元格启用悬停事件并在另一次单击时禁用它吗?
<button id='enable_mode'>Enable</button>
<table>
<tbody>
<tr><td>Package</td><td>1</td></tr>
<tr><td>Cost</td><td>900</td></tr>
</tbody>
</table>
jQuery的:
$('#enable_mode').click(function(){
$(this).text(function(i, text){
return text === "Enable" ? "Enable" : "Disable";
})
var see = $(this).text()
if($(this).text() == "Enable"){
hoverme($('table tbody tr td:nth-child(2)'));
}else{
????
}
});
function hoverme(para) {
$(para).hover(
function() {
$(this ).append('<div id="edit">Edit</div>' );
}, function() {
$( this ).find('#edit').remove();
}
);
}
答案 0 :(得分:1)
这可能是您想要实现的目标: JSFiddle
这是相应的代码。 HTML和CSS代码保持不变,为了清晰起见,我刚添加了几行,以及一些填充和边距。
<强> JS:强>
$('#enable_mode').click(function () {
//Check the text of the button
$(this).text(function (i, text) {
if (text === "Enable") {
//Enable hover state with events on mouseenter and mouseleaves
$("tr").hover(function () {
//On mouseenter, change background color (= hover state)
$(this).css("background-color", "#DDD");
}, function () {
//On mouseleave, change background color to default
$(this).css("background-color", "white");
});
} else if (text === "Disable") {
//Remove mouseenter and mouseleave events.
$("tr").unbind('mouseenter mouseleave');
}
//Toggle the text in the button
return text === "Enable" ? "Disable" : "Enable";
});
});
您可以修改此代码,以便在悬停时执行任何操作,包括附加内容(就像您想要的那样)。
答案 1 :(得分:1)
我已经修改了一点代码以实现DEMO
代码:
var para = $('table tbody tr td:nth-child(2)');
$('#enable_mode').click(function()
{
var that = $(this);
if($(this).text() == "Enable")
{
para.bind('mouseover', mouseOver).bind('mouseout', mouseOut);
that.text("Disable");
}
else
{
para.unbind('mouseover mouseout');
that.text("Enable");
}
});
function mouseOver() {
$(this).append('<div id="edit">Edit</div>' );
}
function mouseOut() {
para.find('#edit').remove();
}