gpt4 book ai didi

javascript - 使用 javascript 将 class 和 id 属性添加到 HTML 标签

转载 作者:行者123 更新时间:2023-12-02 17:53:56 25 4
gpt4 key购买 nike

我编写了以下代码来检索要显示的 xml 数据,但我想创建一个选项卡来存储这些 xml 数据,但我不知道如何使用以下方法将 class 和 id 属性添加到 HTML 标签JavaScript。

我想出了一个简单的代码,如下所示。

document.write("<div></div>");
document.write("<h1><strong>Resources List</strong></h1>");
document.write("<nav>");

document.write("<ul>");
document.write("</ul>");
document.write("<li ><a href=#tabs-1>Humans</a></li>");
document.write("<li ><a href=#tabs-2>Machines</a></li>");
document.write("</ul>");

最佳答案

这有几个问题,并且显然没有足够的信息来提供可靠的答案,但为了提供帮助,让我从这里开始。

我建议使用 jQuery,虽然我不相信它总是正确的答案,但在操作 DOM 时它经常是正确的答案。

我不确定导航标签是什么,但我假设您想要这样的结构。

    <div>
<h1><strong>Resources List</strong></h1>
<ul>
<li ><a href=#tabs-1>Humans</a></li>
<li ><a href=#tabs-2>Machines</a></li>
</ul>
</div>

我见过的最有效的方法,并且用过很多!是

    function (){ // wrapper function, whatever is starting everything
var $div = $( document.createElement('div') ),
$h1 = $( document.createElement('h1') ),
$ul = $( document.createElement('div') ),
$humanLi = $( document.createElement('li') ),
$humanA = $( document.createElement('a') ),
$machineLi = $( document.createElement('li') ),
$machineA = $( document.createElement('a') ),
// while this looks like overkill the research i have done suggests this to be the most efficient means of generating DOM elements
// it also affords you great manipulation ability

$machineA.attr('href', '#tab1').html('2').click( function(e) {
// i realize this wasn't in the code you provided but i thought i would demonstrate
e.preventDefault(); // avoid changing the url on click
}).appendTo( $machineLi );

$humanA.attr('href', '#tab1').html('1').click( function(e) {
// i realize this wasn't in the code you provided but i thought i would demonstrate
e.preventDefault(); // avoid changing the url on click
}).appendTo( $humanLi );

$humanLi.appendTo( $ul );
$machineLi.appendTo( $ul );

$h1.appendTo( $div );
$ul.appendTo( $div );

$div.addClass( 'new-class' /* this is how you add a class */ ).attr('id', 'new-ID' /* this is how you set an id */ );

// at this point you inject your structure wherever you want it
$div.appendTo('body');
// or
$div.appendTo(document);
// or
$div.appendTo( $(' some selector #content or .main whatever ') );
}

关于javascript - 使用 javascript 将 class 和 id 属性添加到 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21127804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com