jquery selector not working with [ ]

岁酱吖の 提交于 2019-12-04 06:19:25

问题


I'm using jQuery to manipulate form data in an osCommerce instance and I'm having trouble selecting some elements.

The script generates textareas with the id product_description[N], N being the 1, 2, 3...

The problem is that having an id value with [] in it makes jQuery (even regular script) not to select the element and I can't work with it.

I tried switching the id to underscores, manipulate the information and then change it back to [ ] but I can't even do:

$('#product_description[1]').attr('id','products_description_1');

Is there a way to make jQuery to select something like this $('#some[2]').function... ?

If not, If there's another way I can change the ID value then it's ok because I can work as usually and then change it back to the [ ] for the php to recognize that field

Yes, I know, I can select the textarea in another way like by class, but as there are many texareas in te page, I need a unique name and that would requiere editing osCommerce script which I don't want. I plan to contribute my JS to the oscommerce community and for another person to just add a .js is easy, but if they have to edit a php file for the javascript to work it could be either too scary for a newbie or impossible for somebody that already edited it.

Thanks a lot


回答1:


Try this:

$('#product_description\\[1\\]')

Note that while this may work, the bracket characters are not valid for use in IDs prior to HTML5 (although they're fine for use in classes).




回答2:


$("#product_description\\[1\\]").attr("id", "products_description_1");

is the right code, look at "ID-Selector" on jQuery.com




回答3:


The [] characters are not valid ID characters in HTML4. Don't expect consistent results in different browsers if you use them.


EDIT:

If you just can't control the format of the IDs on the server side, you could do this:

$("*[id='product_description[1]']")

but it will be terribly slow in browsers that don't support querySelectorAll.

(Note that you shouldn't need the \\ here because of the quotation marks around the value.)



来源:https://stackoverflow.com/questions/4822515/jquery-selector-not-working-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!