有效的jQuery选择器语法?

时间:2016-03-24 21:57:34

标签: javascript jquery html expression

这是有效的语法吗?

$('.' + type).append('<p>' + value + '</p>');

这是完整的部分

$('.submit-items').click(function() {
   var type = $('.food-list .active li').text();
   var value = foodLoads[type];
   $('.' + type).append('<p>' + value + '</p>');
})

每次我点击按钮我都会收到此错误

“jquery.min.js:2未捕获错误:语法错误,无法识别的表达式:。

                mango"

mango是('。food-list .active li')中文本的可能结果之一.text()

这是对象:

  var foodLoads = {
    orange: 6.7,
    apple: 5.6,
    banana: 12.7,
    grapes: 16.3,
    peach: 2.7,
    pear: 6.5,
    mango: 16.1,
    blueberries: 9.3,
    grapefruit: 1.7,
    strawberries: 3.5,
    tangerine: 3.1,
    watermelon: 8,
    duck: 0,
    beef: 0,
    chicken: 0,
    ham: 0,
    turkey: 0,
    elk: 0,
    pork: 0,
    fish: 0,
    eggs: 0,
    lamb: 0,
    applejuice: 11.8,
    cranberryjuice: 23.3,
    orangejuice: 14.4,
    carrotjuice: 8.6,
    lemonade: 24.3,
    hotchocolatemix: 10.2,
    tomatojuice: 3.5,
    chocolatemilk: 13.3,
    almondmilk: 0.02,
    soymilk: 4,
    wholewheatbread: 6.1,
    whitebread: 10.7,
    bagel: 30,
    waffle: 13.8,
    pancake: 5.3,
    croissant: 12.2,
    muffin: 28.8,
    englishmuffin: 21.3,
    doughnut: 15.2,
    oatmeal: 12.6,
    quinoa: 20.4,
    wholegrainbread: 7.1 
  }

1 个答案:

答案 0 :(得分:1)

一切看似合法,但错误信息

jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: .

是由您的选择器未返回任何内容或text()为空而导致的。这里的含义是错误的:

$('.food-list .active li')

如果此选择器没有匹配任何内容,或者text()返回一个空字符串,则会出现那个轻微的神秘错误消息。演示:https://jsfiddle.net/dannyjolie/f386gzzh/

然后由

引起实际的错误

$('.' + type).append('<p>' + value + '</p>')被评估为

$('.').append('<p>' + value + '</p>'),显然失败了。