开发者

JQuery Selector Doesn't Recognize String Created using JS Replace Function

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 t开发者_高级运维he 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)");


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜