javascript - 无法向元素添加类或属性

标签 javascript jquery

我想将个人 ID 添加到我的每个具有“章节”类的 div 标签中。通过放入一个警告框,我检查它确实迭代了 16 个元素,这是预期的,因为这是类“章节”的 div 元素的数量。我尝试添加另一个类(通过 addClass)并向元素添加一个 id,如下所示。但它不起作用。我在这里缺少什么?

JavaScript:

$(document).ready(function() {
    $(".chapter").each(function(index) {
        $(this).attr('id', 'chapter' + index + 1);
    });
});

html:

!DOCTYPE html>
<html>
    <head>
        <title>Programming examples for 70-480</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script type="text/javascript" src="70-480.js"></script>
    </head>
    <body>
        <h1>Programming examples for 70-480</h1>
        <h4>Training Guide Programming in HTML5 with JavaScript and CSS3</h4>
        <ul>
            <div class="chapter"><li>Chapter 1: Getting started with Visual Studio 2012 and Blend for Visual Studio 2012</li>
                <ul>
                    <li>Lesson 1: Visual Studio 2012</li>
                    <li>Lesson 2: Blend for Visual Studio 2012</li>
                </ul>
            </div>
            <div class="chapter"><li>Chapter 2: Getting started with HTML5</li>
                <ul>
                    <li>Lesson 1: Introducing HTML5</li>
                    <li>Lesson 2: Embedding content</li>
                </ul>
            </div>
            ...

最佳答案

这里的问题是因为您的 HTML 无效。 div 元素不允许是直接后代或 ul 元素,并且正在被删除/移动到 DOM 中的其他位置。您应该将 chapter 类添加到顶层 li,然后您的代码才能正常工作。

<ul>
    <li class="chapter">
        Chapter 1: Getting started with Visual Studio 2012 and Blend for Visual Studio 2012
        <ul>
            <li>Lesson 1: Visual Studio 2012</li>
            <li>Lesson 2: Blend for Visual Studio 2012</li>
        </ul>
    </li>
    <li class="chapter">
        Chapter 2: Getting started with HTML5
        <ul>
            <li>Lesson 1: Introducing HTML5</li>
            <li>Lesson 2: Embedding content</li>
        </ul>
    </li>
</ul>

此外,正如@Pointy 建议的那样,您需要将 index + 1 逻辑括在方括号中,以防止它被解释为字符串连接:

$(".chapter").each(function(index) {
    $(this).attr('id', 'chapter' + (index + 1));
});

Example fiddle

关于javascript - 无法向元素添加类或属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26847277/

相关文章:

javascript - Dart Nodejs 和 Socketio

javascript - 我怎样才能选择一个父元素,所有不是第一个的子 div,以及 parent 和他们的 child 的 sibling

javascript - 滚动 iframe 内的 jQuery UI dropzone 错误偏移

javascript - 如何使 dynaTree jQuery 插件中的超链接可点击?

javascript - 将分块文件直接上传到 Amazon s3

javascript - 如何在创建 React 组件时为其初始化 Redux 状态?

javascript - 如何解决 XMLHttpRequest.send 处的 ERROR NetworkError (...dist\fxcore\server\main.js :200768:19)

javascript - “修复所有可自动修复的问题”并没有修复尽可能多的问题 vscode-eslint

javascript - 每次单击按钮时,我都想在两个功能之间切换

jquery - 如果 TD 具有 rowSpan 属性,则将类应用于 TD