jQuery - How can i dynamically add a list item to

2019-04-10 09:32发布

问题:

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)