简体   繁体   中英

Why am I unable to get the value of this input field using jQuery?

I've been trying to figure out what's wrong with my code for a while now, and why it won't let me get the value of my input field.

My code looks like this:

 <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <input type=text id="0.1.2_00_1" value=0> <script> console.log($('#0.1.2_00_1').val()) </script> 

Why doesn't this work? Hopefully I'm not just being really dumb.

如果ID在jquery中带有句点(特殊字符),则必须使用双斜杠将其转义:

console.log($('#0\\.1\\.2_00_1').val());

You need to escape the periods. For example $('#0\\\\.1\\\\.2_00_1')

 <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <input type=text id="0.1.2_00_1" value=0> <script> console.log($('#0\\\\.1\\\\.2_00_1').val()) </script> 

As the jQuery docs on selectors state:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\\]^{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\\\ .

The id contains the . character which, when passed to a JQuery selector, is interpreted as a CSS class qualifier.

It's causing JQuery to look for an element who's id is 0 that uses a CSS class of 1 and another called 2_00_1 .

The official spec. says:

"Using characters except ASCII letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility."

It's better to avoid them, if possible and use just alpha-numeric values for id s.

 <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <input type=text id="x" value=0> <script>console.log($('#x').val())</script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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