JQuery 选择器无法识别使用 JS 替换功能创建的字符串
我在使用 JavaScript 和 JQuery 运行以下代码片段时遇到问题。 listOfDisplayCategories 是一个字符串值数组。
使用 FireBug 进行调试时,我可以看到在 displayCategoryWithoutSpecialChar 中设置的值是我期望的值。
当我尝试在下一个语句中使用该值作为 JQuery 的选择器时,我没有看到我期望的行为。
基本上该值不被识别为有效的选择器。它不会失败或给出错误,它只是没有按照我期望的方式设置背景图像。
如果我对 displayCategoryWithoutSpecialChar 变量中的值进行硬编码,则该值可以正常工作。当我将其用作 JQuery 的选择器时,从该替换函数返回的值似乎不起作用。有人可以帮助我吗?
var displayCategoryWithoutSpecialChar =
listOfDisplayCategories[i].replace(/[^a-zA-Z0-9]+/g, "");
$("#"+displayCategoryWithoutSpecialChar).css("background-image","url(images/Aut.png)");
I'm having problems running the following code snippet using JavaScript and JQuery. listOfDisplayCategories is an array of String values.
When debugging using FireBug I can see that the value set in displayCategoryWithoutSpecialChar is the value that I expect.
When I try to use this value in the next statement as the selector for JQuery I don't see the behavior I expect.
Basically the value isn't recognized as a valid selector. It doesn't fail or give an error, it just doesn't set the background image the way I'm expecting.
If I hardcode the value in the displayCategoryWithoutSpecialChar variable this works properly. It seems like the value returned from this replace function doesn't work when I use it as the selector for JQuery. Can anybody help me?
var displayCategoryWithoutSpecialChar =
listOfDisplayCategories[i].replace(/[^a-zA-Z0-9]+/g, "");
$("#"+displayCategoryWithoutSpecialChar).css("background-image","url(images/Aut.png)");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我遇到的问题是我使用的选择器基于还不存在的 HTML。此代码片段位于创建 HTML 内容的 for 循环内部。我尝试指定的选择器适用于尚未成为文档一部分的 html。在附加 HTML 后移动带有选择器和 CSS 函数的行解决了这个问题。我通过 JQuery 脚本调试到调用 document.getElementById(String) 的位置。此调用没有返回元素。我仍然不清楚为什么对字符串值进行硬编码可以使其起作用。菜鸟错误。
The problem I was having is that the selector I was using was based on HTML that did not yet exist. This code snippet was inside of a for loop that created HTML content. The selector that I was attempting to specify was for html that was not yet a part of the document. Moving the line with the selector and the CSS function after the HTML had been appended fixed the problem. I debugged through the JQuery script to the point where document.getElementById(String) was invoked. This call did not return an element. I'm still unclear why hard-coding the string value allowed this to work. Rookie mistake.