简体   繁体   English

jQuery .data()不返回布尔值; 为什么?

[英]jQuery .data() does not return boolean value; why?

I'm very unexperienced jQuery programmer unable to find a bug in my trivial script. 我是一个没有经验的jQuery程序员,无法在我的琐碎脚本中找到错误。 Could you please help? 能否请你帮忙?

I want to emphasize a checkbox if its state differs from the initial value. 我想强调一个复选框,如果它的状态不同于初始值。 That initial value is stored as data-init attribute. 该初始值存储为data-init属性。 The generated html for checked and unchecked input looks like this: 生成的用于选中和未选中输入的html如下所示:

<td><input checked data-init id="controls-0-modeU" name="controls-0-modeU" type="checkbox" value="y"></td>

<td><input id="controls-1-modeU" name="controls-1-modeU" type="checkbox" value="y"></td>

In the accepted answer here: Retrieve boolean data from data attribute in jquery there is: " The jQuery .data() method is smart about recognizing boolean and numeric values and converts them into their native type ". 在这里接受的答案中: 从jquery的data属性中检索布尔数据,其中有:“ jQuery .data()方法很聪明,可以识别布尔值和数值并将其转换为原始类型 ”。 That is what I want. 那就是我想要的。

My script begins with: 我的脚本开始于:

$(document).ready(function(){
        $("td input:checkbox").change(function(){
            var $init = $(this).data("init")

But the value of $init is either undefined (for initially unchecked input) or an empty string (for initially checked). 但是$init的值是undefined (对于最初未检查的输入)或空字符串(对于最初检查的)。 Both of them evaluate to false. 他们两个都评估为假。 Why am I not getting true/false instead? 为什么我没有得到对/错?

A data attribute is not treated like a boolean attribute by jQuery(like checked, readonly, etc) so you have to give it a value jQuery不会将数据属性视为布尔属性(如选中,只读等),因此您必须为其赋予一个值

<td><input checked data-init="true" id="controls-0-modeU" name="controls-0-modeU" type="checkbox" value="y"></td>

<td><input  data-init="false" id="controls-1-modeU" name="controls-1-modeU" type="checkbox" value="y"></td>

if you want to keep your mark up you'll have to do the heavy lifting yourself 如果你想保持自己的标记,就必须自己做些繁重的工作

var $init = $(this).is("[data-init]");

you can check if the element has the attribute like so: 您可以检查元素是否具有如下属性:

if (!!$(this).attr("data-init")) {
  // its there
}
else {
  // its not
}

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

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