开发者

Why won't my jQuery selector work for IDs with colons and periods in them?

I have a script that's supposed to dynamically 开发者_JAVA技巧place divs containing group member names inside one container div. These divs are ID'd by the concatenation of "groupMemberEntryDiv" and the group member's e-mail address (which is unique in my system).

The problem is that using the IDs in jQuery selectors doesn't work. I believe I've covered all the possible hangups that could be causing this problem:

  1. The presence of '@' in e-mail addresses (element IDs cannot contain this character). I've fixed this by replacing them with ':', which is allowed character. Also, since ':' does not appear in valid e-mail addresses, I can use indexOf to parse the string and replace it with '@' when I need to use the e-mail address again.
  2. The presence of ':' and '.' in (the now modified) e-mail addresses (jQuery may see them as pseudo-classes and classes respectively). Following the instructions in that page, I have tried to escape the characters. In fact, I lifted the .replace() function from that very link to do so.

Unfortunately, the selectors still won't work. I've created a simple jFiddle to illustrate the problem.

Can someone please explain what's going on?


This is because you are escaping the special characters (which is correct for the selector) but the ID doesn't need to be escaped. Consider:

$("#protectedGroupDiv100").append("<div id='groupMemberEntryDiv"  + emailString + "' class='groupMemberEntryDivs'>hey</div>");

Generates:

<div id="groupMemberEntryDivblahblah\:gmail\.com" class="groupMemberEntryDivs"></div>

See how this creates an element with id of: #groupMemberEntryDivblahblah\:gmail\.com but later you use the selector of #groupMemberEntryDivblahblah\:gmail\.com which seems the same but what jQuery looks for is actually #groupMemberEntryDivblahblah:gmail.com. Since the ID of your element has backslashes in it, jQuery finds no match for the selector.

To fix this set the ID before you escape it:

$.each(emailArray, function(index, emailString){
    emailString = emailString.replace("@", ":");            //Element attributes cannot contain "@"

    $("#protectedGroupDiv100").append("<div id='groupMemberEntryDiv"  + emailString + "' class='groupMemberEntryDivs'>hey</div>");

    emailString = emailString.replace(/(:|\.)/g,'\\$1');    //Escape ':' and '.'

   alert($("#groupMemberEntryDiv"  + emailString).length);                  
});

Here is a modified jsFiddle.

Though this works, I do not recomend having user emails in the markup. As others have hinted to it can lead to security issues.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜