繁体   English   中英

如何使用jquery在另一个元素中添加元素

[英]How to add element inside another element with jquery

嘿,我正在尝试使用 jquery 在<li>添加<a>标签,但我正在努力寻找正确的方法。 这是我的代码示例:

$dropdown.find('ul').append($('<li></li>').append($('<a></a>'))
    .attr('href', $option.val())
    .attr('data-display', (display || null))
    .addClass('option ' + customClassEtay +
    ($option.is(':selected') ? ' selected' : '') +
    ($option.is(':disabled') ? ' disabled' : ''))
    .html($option.text())

您可以直接将其添加到列表项字符串中。

作为参考,以这种方式将 html 附加到元素将需要.appendTo()方法。

$('<li><a></a></li>').appendTo('ul').otherChainableMethods();

如果我不得不猜测,你可能正在尝试做这样的事情:

$dropdown.on('change', function() {
  let $option = $(this).find('option:selected');

  $('ul') //most likely not a child of the $dropdown
    .append(`<li><a class="option ${customClassEtay}" data-display="${display || null}" href="${$option.val()}">${$option.text()}</a></li>`);
;})

该选项将是:selected如果您选择它并且在disabled时不可选,所以我不确定您要在那里做什么。

`${}`模板文字

您正在尝试将<a></a>添加到<li></li>对吗? 但是从你上面的代码来看,它不起作用,为什么? 因为<li></li>还没有插入到DOM树中

尝试这样做


$('#someElem').append('<li></li>').delay(3000).append('<a></a>')

这应该有效!

重新定义解决方案

这是在JQuery官网测试的


$('#testingInsert')
// insert the list elem into the <ul> tag with an id that uniquely identified it
.append("<li id='listItem1'>New List Item2</li>")
// fade the newly added list item 
.fadeOut(function(){ 
     // Now search for that newly added list item and add the <a> to into it
     $(this)
    .find('#listItem1')
    .append('<a href="#snoop">A tag elem </a>');

    // That's it, it work perfectly 
}).fadeIn();

我希望这可以帮助您实现您想要实现的目标,因为这只是为了完成任务。

暂无
暂无

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

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