看起来很简单(尽管我仍在学习 jQuery 的来龙去脉)。
这是我的 HTML:
<div id="fbsignup">
<div class="message messageerror">
<strong>There were errors with your registration:</strong>
<ul></ul>
</div>
</div>
这是我的(尝试过的)jQuery:
// Check Required Fields.
$('#fbsignup input.required').each(function () {
if ($(this).val().trim() == '') {
$(this).next('em').html('*').show();
$('#fbsignup .message ul').add('li').html('Fields marked with * are required.');
}
});
这就是它对 DOM 所做的事情:
<div class="message messageerror">
<strong>There were errors with your registration:</strong>
<ul>Fields marked with * are required.</ul>
</div>
它正在将文本添加到内部 html。我希望它添加一个 <li>
带有我设置的内部 html 的元素 - 我认为这就是链接的工作原理?
这是我想要最终得到的 HTML:
<div class="message messageerror">
<strong>There were errors with your registration:</strong>
<ul>
<li>Fields marked with * are required.</li>
</ul>
</div>
我也试过这个:
$('#fbsignup .message ul').add('<li>Fields marked with * are required.</li>');
什么都不做。
我错过了什么?是 .add
函数不适合在这里使用?
最佳答案
您想使用 .appendTo(...)
对于这种风格。
$("<li/>").appendTo("#fbsignup .message ul").html("Fields marked with * are required.");
关于jQuery - 如何动态地将列表项添加到无序列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3446084/