简体   繁体   English

根据用户输入动态生成id选择器

[英]Generating id selector dynamically based on user-input

I am facing a problem in jQuery selector. 我在jQuery选择器中遇到问题。 I am generating selector string dynamically based on user-input as show below :- 我正在根据用户输入动态生成选择器字符串,如下所示:-

jQuery("#" + userInput + "-edit").modal("show")

When the user enters value like "AdvancedResults." 当用户输入"AdvancedResults."类的值时"AdvancedResults." Selector becomes 选择器变为

jQuery("#AdvancedResults.-edit").modal("show")

which does not return expected element, despite the fact that 尽管事实是,它不会返回预期的元素

Am I doing something patchy ? 我在做些杂乱的事情吗? Is there any better way to solve this problem ? 有没有更好的方法来解决这个问题?

Btw, apologising for newbie question, as I am new to JS world. 顺便说一句,为新手问题道歉,因为我是JS世界的新手。

Thanks in advance. 提前致谢。

Just use: 只需使用:

Use the escaping rules from the jQuery selectors API as follows: 使用jQuery选择器API中的转义规则,如下所示:

$("#AdvancedResults\\.-edit").modal("show");

You can replace . 您可以替换。 to \\. 至 \\。 dynamically using str.replace(): 使用str.replace()动态地:

 var str = "AdvancedResults."; str = str.replace(/\\./g, "\\\\."); // it will add add \\\\ dynamically before . console.log($("#"+str+'-edit').length); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <input id="AdvancedResults.-edit" type="text"/> 

如果您的元素确实有一个ID #AdvancedResults.-edit ,即包含一个点,则必须使用jQuery Selectors中的\\\\对其进行转义。

Use [attribute=""] selector in such cases where the parameter is dynamic and might contain special chars not supports by jQuery # - ID selector. 在参数是动态的并且可能包含jQuery # -ID选择器不支持的特殊字符的情况下,请使用[attribute=""]选择器。

jQuery("[id='" + userInput + "-edit']").modal("show")

Example snippet : 片段示例:

 var userInput = "abc."; alert(jQuery("[id='" + userInput + "-edit']").val()) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input id="abc.-edit" value="test"/> 

I have solved it using attribute hack. 我已经解决了使用属性黑客。

It's as follow :- 如下:

jQuery("[id='" + userInput + "-edit']").modal("show");

It worked perfectly for me. 它对我来说效果很好。

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

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