javascript - 查找列表项并将其 ID 转换为小写,添加连字符

标签 javascript jquery find

我在同一个页面上有多个无序列表(准确地说是 Accordion )。每个列表项都有一个唯一的 id,基本上是用户生成的字符(因此可以是任何东西)。我正在尝试将每个唯一 ID 转换为小写并将所有空格替换为连字符。

我正在使用的代码位于 .each 函数中,因为同一页面上有多个 Accordion ,它仍然输出用户生成的 ID 而不是转换后的 ID:

$('ul.responsive-accordion').each(function() {

   var question = $('ul.responsive-accordion').find('li');
   var questionhash = $(question).attr('id');

   convertedhash = questionhash.toLowerCase().replace(/ /g, '-');

});

当我使用下面的输出到控制台时,它只输出第一个项目 ID 两次而不是其他项目(在这个例子中应该显示 3 个列表项目 ID):

// Replace spaces with hyphens
var question = $('ul.responsive-accordion').find('li');
var questionhash = $(question).attr('id');

console.log ( questionhash );

convertedhash = questionhash.toLowerCase().replace(/ /g, '-');

console.log ( convertedhash );

查看输出:

enter image description here

最佳答案

您需要使用 each() 将它们全部循环

$('ul.responsive-accordion li').each( function() {
    var id = $(this).attr('id');
    console.log( id );
    var newId = id.toLowerCase().replace(/ /g, '-');
    console.log( newId );
    $(this).attr('id', newId);
});

关于javascript - 查找列表项并将其 ID 转换为小写,添加连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31744098/

相关文章:

c++ - 希望在 STL vector 中找到 C++ STL vector

jQuery 与 find() 相反

javascript - Sequelize PostgreSQL : query to see if string is within an array

javascript - 确定当前是否正在左键单击按钮(按住单击)?

javascript - 获取数组中没有 double 值的元素

javascript - .load() 在检索内容时是否保留内联 JavaScript?

jquery - CSS 过渡可调高度

javascript - 手机和平板电脑的悬停问题

javascript - 函数中的 jQuery 变量作用域

linux - 要使用哪个 find -exec convert 命令将 n 个 pdf 文件连接成一个文件?9sa