javascript 语法错误,无法识别的表达式:option[value=property name]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28198596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:34:08  来源:igfitidea点击:

Syntax error, unrecognized expression: option[value=property name]

javascriptjquerydatalist

提问by runningmark

I have a datalist which looks like this

我有一个看起来像这样的数据列表

<datalist id="properties">
       <option value="property name"></option>
       <option value="property"></option>
</datalist>

Now I'm using this code to find where values entered by the user is in the list:

现在我正在使用此代码来查找用户输入的值在列表中的位置:

var user_property = $('#user_property').val().toLowerCase(); // taken from input type with id user_property
var pro = $('#properties').find("option[value="+user_property.replace(' ','-')+"]");
if(pro != null && pro.length > 0)
{
    // run some code
}
else
{
    // show error popup
}

I am getting error in var pro = $('#properties').find("option[value="+user_property.replace(' ','-')+"]");

我遇到错误 var pro = $('#properties').find("option[value="+user_property.replace(' ','-')+"]");

Error code says Syntax error, unrecognized expression: option[value=property name]

错误代码说 Syntax error, unrecognized expression: option[value=property name]

How to get rid of this error?

如何摆脱这个错误?

回答by Sudhir Bastakoti

try adding quotes, as:

尝试添加引号,如:

var pro = $('#properties').find("option[value='"+user_property.replace(' ','-')+"']");

or better break it down to:

或者更好地将其分解为:

var replaced = user_property.replace(' ','-');
var pro = $('#properties').find("option[value='"+replaced+"']");

if you want to check for text like "property name" then you could directly do:

如果要检查“属性名称”之类的文本,则可以直接执行以下操作:

var pro = $('#properties').find("option[value='"+user_property+"']");

回答by Sameer Alibhai

Try adding quotes around the value and it will work.

尝试在值周围添加引号,它会起作用。

$('#properties').find("option[value='property name']")

回答by Sadikhasan

You need to add single quote for your value like

您需要为您的价值添加单引号,例如

var pro = $('#properties').find("option[value='"+user_property.replace(' ','-')+"']");