首页 > 解决方案 > 从变量中为每个项目设置 id

问题描述

尝试基于子应用锚点,然后为具有相同值的锚点创建 ID。上半场,锚,正在工作。

应用这个

$(".horizontal-tab-button a").each(function() {
    var anchorid = $(this).attr('href', '#' + $(this).children('strong').html().replace(/ /g,"_").toLowerCase());
    $(".horizontal-tab-button a strong").attr('id', anchorid);
});

对此

<li class="horizontal-tab-button">
  <a href="#">
    <strong>Application</strong>
  </a>
</li>

<li class="horizontal-tab-button">
  <a href="#application">
    <strong id="[object Object]">Application</strong>
  </a>
</li>

错误是[object Object],应该是<strong id="application">

.attr('id' + anchorid);什么都不给。

现场示例https://jsfiddle.net/qyr0xk1e/1/

标签: javascriptjquery

解决方案


这是因为您的变量实际上正在执行一个方法。

var anchorid = $(this).attr(...);

试试这个:

var anchorid = $(this).children('strong').html().replace(/ /g, "_").toLowerCase();

$(".horizontal-tab-button a strong").attr('id', anchorid);
$(".horizontal-tab-button a strong").attr('href', '#' + anchorid);
// don't forget to actually reassign the href, since it has now been moved out of the variable

推荐阅读