javascript - Jquery对使用replaceWith添加的元素没有影响

标签 javascript jquery html

我正在使用replaceWith向多个页面添加通用导航栏。

在replaceWith()之后,我想将“active”类添加到li元素之一以使链接看起来活跃。

该代码对运行时没有影响。但是当我随后在 Chrome Snippets 中运行 $("#link1").addClass("active") 时,它会按预期工作。

<body>
<div id='nav-placeholder'></div>

<script>
        $.get("static/html/navbar.html", function(data){
          $("#nav-placeholder").replaceWith(data);
        });
        //There is an <li> element in navbar.html with id="link1"
        $("#link1").addClass("active");
</script>
</body>

最佳答案

<div id='nav-placeholder'></div>

<script>
        $.get("static/html/navbar.html", function(data){
          $("#nav-placeholder").replaceWith(data);
          $("#link1").addClass("active");
        });        
</script>

关于javascript - Jquery对使用replaceWith添加的元素没有影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41732263/

相关文章:

javascript - 如何将组合框选定的值和单选按钮列表选中的值从 View 传递到 Controller

javascript - 使用 Electron Builder 构建后,Electron 应用程序未加载 index.html,甚至没有给出错误

javascript - 滚动到页面底部,仅当用户在 DOM 操作之前已经位于底部时

javascript - 使用 jQuery 更改 <select> 选项

html - 设置溢出 :auto, 但不显示水平滚动条

php - 将输入按钮更改为图像?

javascript - React hooks 状态不使用最新版本

JavaScript循环混合div

javascript - 如何在数据表中添加行?

html - 允许调整大小以忽略最大高度?