【问题标题】:jQuery - How can i dynamically add a list item to an unordered list?jQuery - 如何将列表项动态添加到无序列表?
【发布时间】:2011-03-27 15:23:56
【问题描述】:

看起来很简单(虽然我还在学习 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。我希望它在我设置的内部 html 中添加一个 &lt;li&gt; 元素 - 我认为这就是链接的工作原理?

这是我想要最终得到的 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 函数不适合在这里使用吗?

【问题讨论】:

    标签: jquery html dom jquery-selectors html-lists


    【解决方案1】:

    您想为这种风格使用.appendTo(...)

    $("&lt;li/&gt;").appendTo("#fbsignup .message ul").html("Fields marked with * are required.");​

    Try it.

    【讨论】:

    • 不错。我更喜欢这个,因为你可以链接选择器(.html)。谢谢
    【解决方案2】:

    试试

    $('#fbsignup .message ul li').add

    【讨论】:

    • 选择器不会返回任何东西,因为没有 li 元素(但 - 这就是重点)
    【解决方案3】:

    对我来说问题似乎是您使用了一个名为 .add() 的函数 我认为没有这样的函数 - 错误。
    可能您可以使用 .append() 来执行您的意愿 http://api.jquery.com/?ns0=1&s=append =)

    对我来说,一个好的一般规则是事先在 Firebug 控制台上尝试一些东西(通过 FireFox)

    【讨论】:

    • .add 肯定是一个函数 (api.jquery.com/add)。我也试过追加,做同样的事情(添加html,而不是html元素)
    • 好的 - 让它与 .append('
    • foo
    • ') 一起使用。遗憾的是参数只是内容而不是实际的 dom 元素(例如 .append('li').html('foo')。无论如何,都很好。谢谢
  • 呵呵 真可惜,.add 是一个函数,只是 API 搜索没有为我指出它:P
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签