As we have seen in the previous lessons, the html() and text() methods can be used to get and set the content of a selected element. However, when these methods are used to set content, the existing content is lost. jQuery has methods that are used to add new content to a selected element without deleting the existing content:
如同我們前面的課程中已看過的,html()和text()方法可以被用來取得和設定選取元素的內容,然而,當使用這些方法去設定內容時,存在的內容會遺失。jQuery有其他的方法可以增加新內容到所選取的元素中,而不會刪除已存在的內容: append() inserts content at the end of the selected elements. prepend() inserts content at the beginning of the selected elements. after() inserts content after the selected elements. before() inserts content before the selected elements.
TIP:Tap Try It Yourself to play around with the code!
提示:按一下Try It Yourself去玩玩看程式碼!
-----
Adding New Elements
增加新元素
The append(), prepend(), before() and after() methods can also be used to add newly created elements. The easiest way of creating a new HTML element with jQuery is the following:
The code above creates a new <p> element, which contains the text Hi and assigns it to a variable called txt. Now, we can use that variable as a parameter of the above mentioned methods to add it to our HTML, for example:
$(function() { var txt = $("<p></p>").text("Hi"); $("#demo").after(txt); })
This will insert the newly created <p> element after the #demo paragraph. You can also specify multiple elements as arguments for the before(), after(), append(), prepend() methods by separating them using commas:
翻譯小心得| 這個單元也把新增的方法介紹得很詳細,只有最後那個多參數的部分,比較沒有詳細的說明,應該是要讓學習者透過實際的練習感受不同的效果吧? 可以注意新增的是<p>標籤,所以有換行的效果,但第2個參數開始,就跟在同一行了喔! Finally, the article above is from SOLOLEARN . I translated it just for practice, personal use only. If that is inappropriate, please contact me.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.