简体   繁体   English

jQuery的html方法中的怪异行为

[英]Weird Behaviour in jQuery's html method

Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'? 任何好的理由为什么$(“p”)。html(0)使所有段落为空而不是包含字符'0'?

Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part. 而不是假设我在jQuery中发现了一个错误,这可能是我的一个误解。

jQuery only accepts a string as an argument for the val parameter of the html() method. jQuery只接受一个字符串作为html()方法的val参数的参数。 If you pass a number like you are it will call the html() method override that sets the contents of the element but the value of the argument will end up being null or an empty string. 如果你传递一个像你一样的数字,它将调用html()方法覆盖设置元素的内容,但参数的值最终将为null或空字符串。

Try this: 试试这个:

$("p").html((0).toString())

Relevant documentation 相关文件

I guess that at some point, it checks if (newContent == false) , and doesn't continue with adding any content? 我想在某些时候,它检查if (newContent == false) ,并且不继续添加任何内容? I tried looking at the source, but got a bit lost... 我试着查看源代码,但有点迷失了......

I also guess that this would not be counted as a bug, since the function calls for a string, and if "0" is passed (as a string), it works as expected. 我也猜测这不会被视为一个错误,因为函数调用一个字符串,如果传递“0”(作为一个字符串),它按预期工作。

A workaround would be to do this: 解决方法是这样做:

var myNum = 0;
$('p').html('' + myNum);

尝试使用text()而不是html()

The code performing the html call was within someone else's plugin and rather than modify it, making upgrading it tedious, I just wrote the following tiny plugin that modifies the html method to do as spoon16 recommended. 执行html调用的代码在别人的插件中,而不是修改它,使升级变得乏味,我只是写了下面的小插件,修改了html方法,就像spoon16推荐的那样。

(function($) {
  var oldHtml = $.fn.html;
  $.fn.html = function (content) {
    oldHtml.apply(this, [content.toString()]);
  }
})(jQuery);

It's a little bit of a hack, but it's working for me and doesn't require me to modify the Plugin I'm using. 这有点像黑客,但它对我有用,并不要求我修改我正在使用的插件。

I just thought someone else might like to see this. 我只是觉得别人可能会喜欢看到这个。

I geuss you missed part of how jQuery works, 我想你错过了jQuery如何工作的一部分,

$('p')

returns all paragraphs and the html( val ) function: 返回所有段落和html(val)函数:

Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).

http://docs.jquery.com/Attributes/html#val http://docs.jquery.com/Attributes/html#val
So if you just want to set the contents for the first p use 所以如果你只想设置第一次使用的内容

$("P").eq(0).html( 'something' );

or to get the html: 或者获取html:

$("P").eq(0).html();

http://docs.jquery.com/Core/eq#position http://docs.jquery.com/Core/eq#position
more on jQuery selectors here: 更多关于jQuery选择器的信息:
http://docs.jquery.com/Selectors http://docs.jquery.com/Selectors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM