jQuery - How can i dynamically add a list item to an unordered list?

夙愿已清 提交于 2019-12-06 05:54:42

问题


Seems like a simple thing to do (although im still learning the ins and outs of jQuery).

Here's my HTML:

<div id="fbsignup">
    <div class="message messageerror"> 
       <strong>There were errors with your registration:</strong> 
          <ul></ul> 
    </div> 
</div>

Here's my (attempted) 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.');
    }
});

And this is what it is doing to the DOM:

<div class="message messageerror"> 
   <strong>There were errors with your registration:</strong> 
      <ul>Fields marked with * are required.</ul> 
</div> 

It's adding the text to the inner html. I want it to add a <li> element with the inner html of what i set - i thought this is how chaining works?

This is the HTML i want to end up with:

<div class="message messageerror"> 
   <strong>There were errors with your registration:</strong> 
      <ul>
         <li>Fields marked with * are required.</li> 
      </ul>
</div>

I also tried this:

$('#fbsignup .message ul').add('<li>Fields marked with * are required.</li>');

Which does absolutely nothing.

What am i missing? Is the .add function not the right thing to use here?


回答1:


You want to use .appendTo(...) for this style.

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

Try it.




回答2:


Try

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




回答3:


The problem for me seems to be that you are using a function called .add() and I don't think there is such function -wrong.
Likely you can use .append() to do your will http://api.jquery.com/?ns0=1&s=append =)

A good general rule for me is to try stuff beforehand on the Firebug console (over FireFox)



来源:https://stackoverflow.com/questions/3446084/jquery-how-can-i-dynamically-add-a-list-item-to-an-unordered-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!