数据属性只返回第一个值

当鼠标悬停在某些列表项上时,我试图让我的页面正文更改颜色。每个列表项都有自己的颜色存储在数据属性中,我可以在 Chrome 检查器中看到它。代码正在做我想做的事情,但是当我希望正文是每个列表项的颜色时,只为每个项目返回列表中的第一种颜色。


HTML:


 <ul class="menu">

    <?php foreach($page->children() as $subpage): ?>

      <li id="tesq" data-color="<?= $subpage->color() ?>">

        <a href="<?= $subpage->url() ?>">

          <?= html($subpage->title()) ?></a>

      </li>

    <?php endforeach ?>

  </ul>

jQuery:


  $(function() {

    $('li').hover(function() {

        $("body").css('backgroundColor', function () {

          return $("#tesq").data('color')

        });

    }, function() {

        $("body").css('backgroundColor', 'lightgrey')

    });

  })

非常感谢任何帮助


幕布斯7119047
浏览 129回答 1
1回答

白衣染霜花

在您当前的代码中,您试图从整个集合中获取数据属性,因此它将返回集合中第一个元素的数据属性值。除了class用于一组元素而不是id(id 在上下文中应该是唯一的 -$("#tesq")将只选择第一个元素)。所以根据悬停的元素来做,你可以this在事件处理程序回调中使用它来引用元素。PHP :&nbsp;<ul class="menu">&nbsp; &nbsp; <?php foreach($page->children() as $subpage): ?>&nbsp; &nbsp; &nbsp; <li class="tesq" data-color="<?= $subpage->color() ?>">&nbsp; &nbsp; &nbsp; &nbsp; <a href="<?= $subpage->url() ?>">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <?= html($subpage->title()) ?></a>&nbsp; &nbsp; &nbsp; </li>&nbsp; &nbsp; <?php endforeach ?>&nbsp; </ul>查询:&nbsp;$(function() {&nbsp; &nbsp; $('.tesq').hover(function() {&nbsp; &nbsp; &nbsp; &nbsp; var $this = $(this);&nbsp; &nbsp; &nbsp; &nbsp; $("body").css('backgroundColor', function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $this.data('color')&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }, function() {&nbsp; &nbsp; &nbsp; &nbsp; $("body").css('backgroundColor', 'lightgrey')&nbsp; &nbsp; });&nbsp; })回调在这里完全没有必要,你可以避免它。&nbsp;$(function() {&nbsp; &nbsp; $('.tesq').hover(function() {&nbsp; &nbsp; &nbsp; &nbsp; $("body").css('backgroundColor', $(this).data('color'));&nbsp; &nbsp; }, function() {&nbsp; &nbsp; &nbsp; &nbsp; $("body").css('backgroundColor', 'lightgrey')&nbsp; &nbsp; });&nbsp; })
打开App,查看更多内容
随时随地看视频慕课网APP