jquery简单交换p元素?

时间:2010-11-28 04:52:39

标签: javascript jquery html

给出像这样的p元素: <p>Something</p>我希望,当用户将鼠标放在它上面时,我们会<p><a href="blabla.org">go here</a></p>

在鼠标离开p区域后悬停,返回上一个: <p>Something</p>州。

我可以举一个像这样的简单例子吗?

非常感谢, MEM

3 个答案:

答案 0 :(得分:2)

或简单修改Ken Redler的原作,使用.data()跟踪事物:

$('p#someID').hover( 
    function() {
        var $this = $(this);
        $this.data('orig', $this.html()).html('<a href="blabla.org">go here</a>');
    },
    function() {
        var $this = $(this);
        $this.html($this.data('orig')).removeData('orig');
    }
);

http://www.jsfiddle.net/ambiguous/FhET2/1/

答案 1 :(得分:1)

更新:正如@Phrogz指出的那样,我错过了部分问题。使用闭包或使用data()捕获状态的建议是好的,但这是另一种方式(使用有趣数量的移动部件):

$(document).ready( function(){
  $('p#someID').hover( 
    function() { // on mouseEnter
      $(this)
        .contents()
        .wrap('<span class="hide"/>') // wrap 'n' hide
        .end() // back to 'this'
        .append('<a href="blabla.org">Fascinating Link!</a>'); // add link
  }, function() { // on mouseLeave
      $(this)
        .find('a')
        .remove() // kill the anchor
        .end() // back to 'this'
        .find('span.hide') // the wrapper
        .contents() // the wrapped
        .unwrap(); // kill the wrapper, leaving its contents
  });
});

这假设是这样的风格:

span.hide {
  display: none;
}

更新示例:http://www.jsfiddle.net/redler/HAGzH/1/

答案 2 :(得分:0)

  $('p#IDHERE').hover( 
    function(){ // on mouseEnter
      $(this).contents().replaceWith('<a href="blabla.org">go here</a>');
    },
    function(){ // on mouseLeave
      $(this).contents().replaceWith("something");
    }
  );

这将取代所有文字