Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery忽略未定义变量_Jquery_Var - Fatal编程技术网

jQuery忽略未定义变量

jQuery忽略未定义变量,jquery,var,Jquery,Var,我正在制作一个建议工具,用于在jQuery中添加变量 某些多项选择题答案具有特定的数据属性,需要将其保存到特定的变量中。如果用户稍后单击相同的数据属性,则必须将该值添加到先前的值(存储在var中) 问题是:不是每个答案都有数据属性。每次用户单击没有数据属性的答案时,该变量都会变为“未定义”,并且变得不可用 我将代码的一个简短版本转换为JSFIDLE来演示这个问题: //默认值为0 var count_health=0; var count_fat=0; $('.question div')。单

我正在制作一个建议工具,用于在jQuery中添加变量

某些多项选择题答案具有特定的数据属性,需要将其保存到特定的变量中。如果用户稍后单击相同的数据属性,则必须将该值添加到先前的值(存储在var中)

问题是:不是每个答案都有数据属性。每次用户单击没有数据属性的答案时,该变量都会变为“未定义”,并且变得不可用

我将代码的一个简短版本转换为JSFIDLE来演示这个问题:

//默认值为0
var count_health=0;
var count_fat=0;
$('.question div')。单击(函数(){
//我想从答案中得到数据
var gather_health=$(this.attr(“数据健康”);
var gather_fat=$(this.attr(“数据fat”);
//并将其添加到变量中
计数健康=+计数健康++收集健康;
count\u fat=+count\u fat++聚集\u fat;
//并展示它
$('.health').text('您的健康状况为:'+count_health');
$('.fat').text('您的fat是:'+count_fat');
});
。问题组{
背景色:#F4;
填充物:5px;
光标:指针;
宽度:50px;
边缘顶部:5px;
}
.健康{
显示:块;
明确:两者皆有;
}

你跑步吗?
对
不
你吃水果吗?
对
不
你吃薯条吗?
对
不

您可以像这样将其计为零(我使用了三元运算符,但您可以很容易地使用if/else语句):


您可以使用或
|
运算符,如下所示:

var-gather_-health=$(this.attr(“数据健康”)| | 0;//或“”或任何默认设置

//默认值为0
var count_health=0;
var count_fat=0;
$('.question div')。单击(函数(){
//我想从答案中得到数据
var gather_health=$(this.attr(“数据健康”)| | 0//
你跑步吗?
对
不
你吃水果吗?
对
不
你吃薯条吗?
对
不

那么,如果它没有属性,你想怎么办?@EvanMosseri Nothing..或者将其视为“0”。它只需要使用当前的数据。这非常简单。感谢您的快速解决方案:-)感谢您的努力!if/else语句的问题在于,它对于许多变量和答案都是不实用的。我认为Mamdouh的答案版本较短,对吗?我很欣赏您的独创性!:-)
// The default is 0
var count_health = 0;
var count_fat = 0;

$('.question div').click(function(){

  // I want to get the data from the answer
  var gather_health = (typeof $(this).attr("data-health") != "undefined") ? $(this).attr("data-health") : 0;
  var gather_fat = (typeof $(this).attr("data-fat") != "undefined") ? $(this).attr("data-fat") : 0;

  // And add it up to the variable
  count_health = +count_health + +gather_health;
  count_fat = +count_fat + +gather_fat;

  // And show it
  $('.health').text('Your health is: ' + count_health);
  $('.fat').text('Your fat is: ' + count_fat);
});