2010-08-10 59 views
4

看起來像一個簡單的事情(雖然即時通訊仍然在學習jQuery的來龍去脈)。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功能在這裏使用不正確嗎?

回答

5

你想使用.appendTo(...)這種風格。

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

Try it.

+0

不錯,我更喜歡這個,因爲你可以鏈接選擇器(.html) 。 謝謝 – RPM1984 2010-08-10 04:59:07

0

對我來說,問題似乎是,你正在使用)叫。新增的功能(我不認爲有這樣的功能 -wrong。
可能是你可以使用.append()做你的意志http://api.jquery.com/?ns0=1&s=append =)

對我來說是一般的規則是事先嚐試的東西Firebug控制檯(超過火狐)

+0

。新增當然是一個函數(http://api.jquery.com/add/)。我也嘗試追加,做同樣的事情(添加html,而不是HTML元素) – RPM1984 2010-08-10 04:49:40

+0

行 - 讓它與.append('

  • foo
  • ')。恥辱參數只是內容而不是實際的dom元素(例如.append('li')。html('foo')。無論如何,一切都很好。謝謝 – RPM1984 2010-08-10 04:53:30

    +0

    hehe恥辱我,.add是一個函數,它只是API搜索沒有爲我指出:P – 2010-08-10 05:00:34

    0

    上嘗試

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

    +0

    選擇器不會返回任何東西,因爲沒有li元素(但是 - 這是整個點) – RPM1984 2010-08-10 04:50:28