【问题标题】:Change inner HTML on hover在悬停时更改内部 HTML
【发布时间】:2014-09-28 06:49:39
【问题描述】:

我对 jQuery 和 Javascript 开发非常陌生。我很快就构思了一个网站导航的想法,该网站导航利用 html 数据标签来生成链接描述。我已经在小提琴here 中设置了它。我的问题是 jquery 没有按预期运行。我太新了,无法确定错误可能是什么。我将不胜感激任何提示。提前谢谢!

这里是 jquery 的代码 sn-p:

$(document).ready(function () {
$(".nav-button").hover(function (e) {
    var description = this.data('title') + ' <span>' + this.data('description') + '</span>';
    document.getElementById('nav-description').innerHTML = description;

}, function (e) {
    document.getElementById('nav-description').innerHTML = '';
});
});

【问题讨论】:

    标签: javascript jquery innerhtml


    【解决方案1】:

    您没有将 this 包装为 jQuery 对象。

    var description = $(this).data('title') + ' <span>' + $(this).data('description') + '</span>';
                     ^^^
    

    当您使用它时,不妨将 jQuery 也用于另一行。

    $('#nav-description').html(description);
    

    【讨论】:

      【解决方案2】:

      jQuery 方式应该是这样的:

      $(function () {
          $(".nav-button").hover(function (e) {
              var description = $(this).data('title') + ' <span>' + $(this).data('description') + '</span>';
              $('#nav-description').html(description);
          }, function (e) {
              $('#nav-description').empty();
          });
      });
      

      建议:

      1. 不要将原生 javascript getElementById() 等与 jQuery 选择器网格化。

      2. 使用$(function () {}); 模式而不是document.ready

      【讨论】:

      • 使用.empty 而不是.html('')
      【解决方案3】:

      this 在 jQuery 事件处理程序范围内指的是 DOM 元素而不是 jQuery 对象。 所以你需要用$ 包裹this 给你jQuery 版本,即$(this)

      jQuery 的工作方式你应该发现以下是正确的$(this)[0] === this。即 jQuery 对象将有一个由选择器匹配的 DOM 元素数组。

      我认为因为您是 jQuery 新手,所以这可能会有所帮助....

      http://www.learningjquery.com/2007/08/what-is-this/

      this 是一个 DOM 元素

      什么时候是 DOM 元素?简短的回答是——通常。使用 jQuery 编写脚本经常涉及到回调函数的使用。无论是处理事件、迭代节点集合、动画图像还是应用动态过滤器,回调都用于在适当的时间调用您的自定义代码。为了方便您,jQuery 将回调函数的范围设置为作为回调主题的元素。

      ... 并重写您的代码

      $(document).ready(function () {
          $(".nav-button").hover(function (e) {
              var $this = $(this),
                  description = $this.data('title') + ' <span>' + $this.data('description') + '</span>';
              $('#nav-description').html(description);            
          }, function (e) {
              $('#nav-description').html('');
          });
      });
      

      【讨论】:

      • 非常感谢您提供额外的阅读材料。这对我非常有益!
      【解决方案4】:

      其实this是指没有data()方法的列表节点

      所以你应该使用dataset 类似的属性

      应该是

      this.dataset['title'];
      this.dataset['description'];
      

      而不是

      this.data('title');
      this.dataset('description');
      

      DEMO

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-30
      • 2014-04-11
      • 1970-01-01
      • 2013-07-21
      • 2013-09-19
      • 2014-06-17
      • 1970-01-01
      • 2020-10-15
      相关资源
      最近更新 更多