jQuery html()函数

本文探讨了使用jQuery的html()函数时遇到的问题,即元素内容必须包裹在<div></div>中才能正确获取。通过示例代码展示了在不同情况下html()函数的输出结果,指出当元素未被<div>包围时,函数返回为空。同时,文章提到了浏览器的差异可能导致HTML内容获取不一致,并引用了API描述进行解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用jQuery的html()函数获取元素内容,发现必须被<div></div>包含,否则获取的就是空

1、

var $template=$('<div><li id="mcity" data-role="list-divider"></li></div>');

console.log($tempalate.html());

//输出<li id="mcity" data-role="list-divider"></li>

2、

var $template=$('<li id="mcity" data-role="list-divider"></li>');

console.log($tempalate.html());

//输出空


查看API描述


 Get the HTML contents of the first element in the set of matched elements.

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:

$('div.demo-container').html();

In order for the following <div>'s content to be retrieved, it would have to be the first one with class="demo-container" in the document:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
</div>

The result would look like this:

<div class="demo-box">Demonstration Box</div>

This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

但是没说没有div就空???

有人提到
.html(),.text(),
这两种用法往往用在div和span元素上 ,一般是为这两种元素进行赋值和取值。

.html()替代了以前的 .innerHTML , .html('test') ,则是替代了 .innerHTML = 'test';

也许是这个原因吧,有知道的告诉我,谢谢!




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值