结合.hover()和.replaceWith()

sal*_*cod 2 jquery

我不能简单.replaceWith()地与a合作.hover().会感激一些帮助.

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

的jsfiddle的人还跟代码来看看.

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

Tho*_*son 5

问题是当你更换它时它会失去id属性.因此,虽然事件的mouseout功能hover()触发它无法找到元素#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');
      }
    );
});
Run Code Online (Sandbox Code Playgroud)

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

如果你想使用replaceWith:

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