结合.hover()和.replaceWith() [英] Combining .hover() and .replaceWith()

查看:57
本文介绍了结合.hover()和.replaceWith()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让这个简单的 .replaceWith()合作.hover() 。会感激一些帮助。

I can't get this simple .replaceWith() to co-operate with a .hover(). Would appreciate some help.

当我将鼠标悬停在它上面时,我希望将文本更改为EXPAND,并在鼠标输出时返回SHOWS。我可以将文本更改为EXPAND,但我无法将文本恢复为原始的SHOWS。

I want it the text to change to EXPAND when I hover on it, and go back to SHOWS when I mouseout. I can get the text to change to EXPAND, but I can't get the text to go back to the original, SHOWS.

适用于任何人的 JSFiddle 代码看看。

The JSFiddle code for anyone kind enough to have a look.

$(document).ready(function() {   
   $("p").hover(
      function () {
        $('#shows').replaceWith('<h2>Expand</h2>');
      }, 
      function () {
        $('#shows').replaceWith('<h2>Shows</h2>');
      }
    );
});


推荐答案

问题是当你要更换它时会丢失 id 属性。因此,虽然 hover()事件的 mouseout 函数触发但它找不到元素 #shows

The problem is when you're replacing it it's losing the id attribute. So although the mouseout function of the hover() event fires it can't find the element #shows.

请改为尝试:

// Change H1 text to "EXPAND" when hovered on, and go *back* to "SHOWS" when the mouse leaves

$(document).ready(function() {   
   $("p").hover(
      function () {
        $('#shows').text('Expand');
      },
      function () {
        $('#shows').text('Shows');
      }
    );
});

你应该总是使用 .text()或者像这样的示例中的 .html()因为实际上你想要做的就是改变TEXT的内部位或中包含的HTML< h2> 标记,而不是整个元素。

You should always use .text() or .html() in examples like this because acctually all you want to do is change the inner bit the TEXT or the HTML contained within the <h2> tag, rather than the whole element.

如果你想使用replaceWith:

If you want to use replaceWith:

$(document).ready(function() {   
   $("p").hover(
      function () {
        $('#shows').replaceWith('<h2 id="shows">Expand</h2>');
      },
      function () {
        $('#shows').text('<h2 id="shows">Shows</h2>');
      }
    );
});

这篇关于结合.hover()和.replaceWith()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆