[英]How to add element inside another element with jquery
Hey I'm trying to add <a>
tag inside <li>
with jquery and I'm struggling to find the right way.嘿,我正在尝试使用 jquery 在
<li>
添加<a>
标签,但我正在努力寻找正确的方法。 here is my code example :这是我的代码示例:
$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())
您可以直接将其添加到列表项字符串中。
For reference, appending html to an element that way would require the .appendTo() method.作为参考,以这种方式将 html 附加到元素将需要.appendTo()方法。
$('<li><a></a></li>').appendTo('ul').otherChainableMethods();
If I had to guess, you're probably trying to do something like this:如果我不得不猜测,你可能正在尝试做这样的事情:
$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>`);
;})
The option will be :selected
if you select it and isn't selectable when disabled
, so I'm not sure what you're trying to do there.该选项将是
:selected
如果您选择它并且在disabled
时不可选,所以我不确定您要在那里做什么。
The `${}`
are template literals . `${}`
是模板文字。
You are trying to add an <a></a>
into <li></li>
right?您正在尝试将
<a></a>
添加到<li></li>
对吗? But from your code above it would not work why?但是从你上面的代码来看,它不起作用,为什么? Because the
<li></li>
has not yet been inserted into the DOM
tree因为
<li></li>
还没有插入到DOM
树中
try doing this尝试这样做
$('#someElem').append('<li></li>').delay(3000).append('<a></a>')
This should work!这应该有效!
$('#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();
I hope this help you achieve what you wanted to achieve, as this is just thwack to get things done.我希望这可以帮助您实现您想要实现的目标,因为这只是为了完成任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.