使用Jquery附加多个html元素 [英] Appending multiple html elements using Jquery

查看:60
本文介绍了使用Jquery附加多个html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是jQuery的新手,想知道是否有什么可以为我提供最佳实践的建议...

Am new to jQuery and wondering if any could advise me on best practise...

我要在页面上添加一个div元素,其中包含很多html,并且不确定实现此目的的最佳方法是....或者是否建议使用jquery ...

I am looking to append a div element to the page, which contains a lot of html and not sure what the best way to achieve this is....or if it is advisable using jquery...

例如,如果我想使用jquery将以下代码附加到页面上,什么是最好的方法?

For example, if I wanted to append the following code to the page using jquery, what is the best way.

<div id="test">
    <h1>This is the test</h1>
    <p>Hello, just a test</p>
    <a href="www.test.com">Click me</a>
    <a href="www.test.com">Click me again</a>
</div>

推荐答案

如果您想按原样添加HTML,则只需使用jQuery append函数. 例如:

If you want to add the HTML as it is, then just use the jQuery append function. For example:

$('body').append('
<div id="test">\
    <h1>This is the test</h1>\
       <p>Hello, just a test</p>\
       <a href="www.test.com">Click me</a>\
       <a href="www.test.com">Click me again</a>\
</div>');

根据需要将选择器从主体更改为其他DOM元素/选择器.

Change the selector from body to other DOM element/selector according to your requirement.

或者,如果文档中已经有ID为"test"的div元素,则可以使用html()函数来设置内容,如下所示:

Or if you already have the div element with ID "test" in the document, then you can set the content using the html() function like below:

$("#test").html('<h1>This is the test</h1>\
       <p>Hello, just a test</p>\
       <a href="www.test.com">Click me</a>\
       <a href="www.test.com">Click me again</a>');

这篇关于使用Jquery附加多个html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆