简体   繁体   English

如何创建一个<a></a>里面<li></li>所有的都在里面<ul></ul>用 JS

[英]how to create a <a></a> inside <li></li> all of the are inside <ul></ul> with JS

I have this ul which is made by HTML and I want to create elements inside with JS我有这个由 HTML 制作的 ul,我想用 JS 在里面创建元素

HTML code: HTML 代码:

<ul id="navbar__list">
    
</ul>

and JS code:和JS代码:

var ul = document.getElementById("navbar__list");
var link1 = document.createElement("a");
var Li1 = document.createElement("li").appendChild(document.createElement("a"));
var sec1 = ul.appendChild(Li1)
link1.innerHTML = "Section 1"
link1.href ="#section1"

all I got was without text and as a beginner, I do not know what is wrong我得到的只是没有文字,作为初学者,我不知道出了什么问题

You need to pass link1 into your appendChild call.您需要将link1传递到您的appendChild调用中。 Right now your code is calling createElement("a") twice and passing the second uninitialized <a> into appendChild , which is not what you want.现在您的代码调用createElement("a")两次并将第二个未初始化<a>传递给appendChild ,这不是您想要的。

You'll want this:你会想要这个:

  • Use const for locals that shouldn't be reassigned.对不应重新分配的本地人使用const
  • Be defensive: because JavaScript doesn't offer compile-time type-safety or other guarantees it's a good idea to always check your assumptions and to throw new Error when those assumptions are invalidated.保持防御:因为 JavaScript 不提供编译时类型安全或其他保证,因此最好始终检查您的假设并在这些假设无效时throw new Error This greatly aids debugging in JavaScript ( "fail fast" ).这极大地帮助了 JavaScript( “快速失败” )中的调试。
  • When building-up DOM element trees in JS, I find it helpful to put each element in its own anonymous-scope ( { } ) which mirrors the DOM's structure.在 JS 中构建 DOM 元素树时,我发现将每个元素放在其自己的匿名范围( { } )中会很有帮助,这反映了 DOM 的结构。
    • This also helps prevent bugs where elements aren't parented correctly.这也有助于防止元素没有正确父级的错误。
const ul = document.getElementById("navbar__list");
if( !ul ) throw new Error( "Couldn't find navbar__list" );

{
    const li = document.createElement("li");
    ul.appendChild( li );

    {
        const aLink = document.createElement("a");
        aLink.textContent = "Section 1";
        aLink.href        = "#section1";

        li.appendChild( aLink );
    }
}

Somewhat surprisingly, the DOM API is kinda verbose: there's no succinct way to create elements with their attributes and inner-content set, instead we need explicit calls to createElement and appendChild .有点令人惊讶的是,DOM API 有点冗长:没有简洁的方法来创建具有属性和内部内容集的元素,相反,我们需要显式调用createElementappendChild Some alternatives have been proposed that use compile-time techniques, like JSX , as a more lightweight alternative you could use a helper-function like this:已经提出了一些使用编译时技术的替代方案,例如JSX ,作为更轻量级的替代方案,您可以使用这样的辅助函数:

/**
    @param {string} tagName
    @param {[string, string][]} attributes - Array of 2-tuples
    @param {HTMLElement | HTMLElement[] | string} content - Either: one-or-many HTML elements, or string textContent
*/
function create( tagName, attributes, content ) {
    
    const e = document.createElement( tagName );
    
    for( let i = 0; i < attributes.length; i++ ) {
        const pair = attributes[i];
        
        e.setAttribute( pair[0], pair[1] );
    }

    if( typeof content === 'string' ) {
        e.textContent = content;
    }
    else if( Array.isArray( content ) ) {
        for( const child of content ) {
            e.appendChild( child );
        }
    }
    else if( typeof content === 'object' && content !== null ) {
        e.appendChild( content );
    }

    return e;
}

Used like so:像这样使用:

const ul = document.getElementById("navbar__list");
if( !ul ) throw new Error( "Couldn't find navbar__list" );

{
    ul.appendChild(
        create( "li", [], create( "a", [ [ "href", "#section1" ] ], "Section 1" ) )
    );
}

Use this:用这个:

var ul = document.getElementById("navbar__list");

var li = document.createElement("li");
ul.appendChild(li);

var link = document.createElement("a");
link.setAttribute('href', '#section1');
link.innerHTML = "Section 1";

li.appendChild(link);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM