jquery:在一行中创建多个元素(jquery: create multiple elements in one line)

编程入门 行业动态 更新时间:2024-10-26 17:30:12
jquery:在一行中创建多个元素(jquery: create multiple elements in one line)

我有以下示例,其中我将嵌套元素添加到DOM:

$ul = $('<ul>').appendTo($('#test'));
$('<li>').text('Item 1').appendTo($ul); 
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div> 
  
 

无论如何,我可以在一行中编写两个javascript行。 我试过以下无济于事:

$('<li>').text('Item 1').appendTo($('<ul>')).appendTo($('#test'))

请注意, <ul>元素不会被添加: https : //jsfiddle.net/upnchucq/

I have the following example in which I'm adding nested elements to the DOM:

$ul = $('<ul>').appendTo($('#test'));
$('<li>').text('Item 1').appendTo($ul); 
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div> 
  
 

Is there anyway I can write the two javascript lines in one line. I've tried the following to no avail:

$('<li>').text('Item 1').appendTo($('<ul>')).appendTo($('#test'))

Notice the <ul> element does NOT get added: https://jsfiddle.net/upnchucq/

最满意答案

你错了一个括号。

代码应如下所示:

$('<li>').text('Item 1').appendTo($('<ul>').appendTo($('#test')));

小提琴: https //jsfiddle.net/upnchucq/2/

You misplaced one parentheses.

The code should look like:

$('<li>').text('Item 1').appendTo($('<ul>').appendTo($('#test')));

Fiddle: https://jsfiddle.net/upnchucq/2/

更多推荐

https,$ul,javascript,电脑培训,计算机培训,IT培训"/> <meta name="descript

本文发布于:2023-07-20 12:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1199629.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   元素   jquery   create   line

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!