【问题标题】:Jquery on hover html text change悬停html文本更改上的Jquery
【发布时间】:2012-05-10 12:23:37
【问题描述】:

我有一个如下所示的按钮。 我有一个按钮列表。 当用户单击它时,我运行一个 javascript 函数并发出一个 ajax 请求,如果请求响应成功,则我更改按钮标签的状态属性。我将它从 1 更改为 2。

当属性 status=1 时,我希望用户在将鼠标悬停在按钮上时看到一些文本。

当属性 status=2 时,我不希望他在按钮悬停时看到任何内容。

我尝试如下,但在 status=2 之后,悬停时按钮文本仍然会发生变化。 我怎样才能解决这个问题?

<button onclick="dosomething()" id="someid" status="1">name</button>

<script>
function dosomething(){
    $.ajax({
        type:"GET",
        url:"somefile.php",
        success : function(data) {
            if (data == '200') {
                $('#someid').attr('status', '2');
            }
        },
        error : function() {
            alert('error');
        },
    })
}

$(document).ready(function() {
    updateHoverStates()
});

$(document).change(function () {
    updateHoverStates()
});

function updateHoverStates() {
    $('button[status=1]').hover(
        function () {
            $(this).text('You are hovering');
        },
        function () {
            $(this).text('You are not hovering');
        }
    );
}
</script>

【问题讨论】:

  • 你真的应该在javascript中设置你的点击处理程序;此外,您所有的 jQuery 都应该在 $(document).ready(...) 内。这段代码真是一团糟。
  • 我认为最好使用 css 类而不是 status 属性来保持您的 html 有效...

标签: javascript jquery hover jquery-hover


【解决方案1】:

这可能有效,这样事件在每次调用时都会检查状态属性,而不是在绑定时只检查一次。

function updateHoverStates() {
    $('button[status]').hover(
        function () {
            if($(this).attr('status') == '1')
                $(this).text('You are hovering');
        },
        function () {
            if($(this).attr('status') == '1')
                $(this).text('You are not hovering');
        }
    );
}

作为旁注,我相信data-status 将是一种更好地支持自定义属性的方式,这也将允许使用.data('status') 而不是.attr('status')

或者你也可以使用 CSS 来模拟

button[status="1"]:hover {
    //possible attributes here
}

【讨论】:

  • 我想这会花费更多的计算时间。但这按我的意愿工作:) 谢谢
【解决方案2】:

jsFiddle:http://jsfiddle.net/ajzsv/20/

<button onclick="dosomething()" id="someid" status="1">name</button>

<script>
function dosomething()
{
    $('#someid').attr('status', '2');
    $('#someid').unbind('hover');
}

$(document).ready( function()
{
    $('button').each( function()
    {
        $(this).hover(
        function ()
        {
            $(this).text('You are hovering');
        },
        function ()
        {
            $(this).text('You are not hovering');
        });
    });
});
</script>​

【讨论】:

    【解决方案3】:

    change 事件不会冒泡到文档中,因此updateHoverStates 可能不会被第二次调用。

    【讨论】:

    • 使用 stop() 然后 live() 或 toggle() 怎么样?您能否切换悬停事件并每次设置不同的属性,从而更改按钮上的文本?
    【解决方案4】:

    您曾经为匹配选择器button[status=1] 的所有按钮设置了悬停功能。您稍后更改了 status 属性,但这并没有将悬停事件侦听器与这些按钮分离。

    在你设置的函数中

    $('#someid').attr('status', '2');
    

    您应该手动移除事件监听器。

    $('#someid').unbind('hover');
    

    【讨论】:

    • 谢谢,但我不喜欢取消绑定悬停,因为在更改状态属性后我使用另一个悬停功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多