[英]How to toggle hover event for another selector on click?
Please take a look at this fiddle 请看看这个小提琴
Would anyone please tell me how to enable a hover event for the table cells on clicking the button #edit_mode
and disable it on another click? 有人能告诉我如何在单击
#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: 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();
}
);
}
This might be what you want to achieve: JSFiddle 这可能是您想要实现的: JSFiddle
And here's the corresponding code. 这是相应的代码。 HTML and CSS code stays the same, I've just added a few more rows for clarity, and some padding and margin.
HTML和CSS代码保持不变,为清楚起见,我只添加了几行,并添加了一些填充和边距。
JS: 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";
});
});
You can modify this code to do practically anything on hover, including appending things (like you wanted to do). 您可以修改此代码以在悬停时执行几乎所有操作,包括添加操作(如您想要的那样)。
I have modified your code little bit to achieve your what DEMO 我已经稍微修改了您的代码以实现您的演示
Code: 码:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.