【问题标题】:How to append content from one element to another on hover event如何在悬停事件中将内容从一个元素附加到另一个元素
【发布时间】:2013-04-18 21:12:06
【问题描述】:

所以我有四个标题链接,我想从中获取属性值并附加到外部的空 div。

这里是jsFiddle

我遇到问题的部分是 javascript

$('li a.link').hover(
    function(){
        $(this).text().appendTo('.container');
    });

我不在乎我是抓取属性值还是里面的文本,但似乎都不起作用。我已经让空 div 说“Hello World!”当我将鼠标悬停在链接上时,我无法获取标题值或 HTML 中的文本,感谢您提供任何帮助。

【问题讨论】:

    标签: jquery events dom


    【解决方案1】:

    我认为如果这是一个悬停,即使你也希望文本在“Li a”的鼠标离开时消失,所以我为你做了一个 jsFiddle 示例来完成这两个操作。请检查一下,如果有任何问题,请随时提出。

    $(document).on('mouseenter','li a',function(){
        $('.container').text($(this).attr('title'));
    }).on('mouseleave','li a', function(){
        $('.container').text('');
    });
    

    http://jsfiddle.net/danieljordan13/JfGhY/11/

    【讨论】:

      【解决方案2】:
      $('li a.link').hover(function(){
              var title = $(this).attr('title');
              $('.container').append(title);
      });
      

      Fiddle

      【讨论】:

        【解决方案3】:

        我建议,如果你想附加文本:

        $('li a').hover(
            function(){
                var text = $(this).text();
                $('.container').text(function(i,t){
                    return t + ' ' + text;
                });
            });
        

        JS Fiddle demo.

        或者,如果你想替换文本:

        $('li a').hover(
            function(){
                var text = $(this).text();
                $('.container').text(text);
            });
        

        JS Fiddle demo.

        重新阅读问题后,发现您想使用 title 属性,我建议您改为:

        $('li a').hover(
            function(){
                var title = this.title;
                $('.container').text(title);
            });
        

        JS Fiddle demo.

        参考资料:

        【讨论】:

          【解决方案4】:

          我更喜欢在appendTo()之前使用append()

          这行得通:

          $('.container').append($(this).text());
          

          http://jsfiddle.net/JfGhY/5/

          附加标题:

          $('.container').append($(this).attr('title'));
          

          http://jsfiddle.net/JfGhY/10/

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-12-22
            • 1970-01-01
            • 2012-10-30
            • 1970-01-01
            • 2015-03-25
            • 1970-01-01
            • 2017-03-18
            • 1970-01-01
            相关资源
            最近更新 更多