I have the following input elements:
<input id="AAA_RandomString_BBB" type="text" />
<input id="AAA_RandomString_BBB_Start" type="text" />
<input id="AAA_RandomString_BBB_End" type="text" />
AAA & BBB are constants and I will always know what they are. However RandomString will always be random.
I want to get the value of AAA_RandomString_BBB. I do not want the values from the input elements with ID ending in either _Start or _End.
I tried the folowing:
$('[id^="AAA_"]')
But the above selects all of the input elements that have an ID starting with "AAA_"
I need some way to select using a regex type syntax like:
$('[id^="AAA_(.+?)_BBB"]')
Is this possible? If not, can anyone suggest a method of selecting
You can combine both selectors in a multiple attribute selector .
$("[id^=AAA_][id$=_BBB]")
It will return all the elements that matches all the specified attribute filters:
[id^=AAA_]
matches elements with id
attribute starting with AAA_
, and [id$=_BBB]
matches elements with id
attribute ending with _BBB
. Another generic alternatives:
:regex()
selector , .filter()
-based approach . You can look for id's starting with AAA
and ending with BBB
like this:
$("[id^=AAA_][id$=_BBB]")
The working fiddle: http://jsfiddle.net/DN9uV/
This can be done like so:
$('input').filter(function(){ return this.id.match(/^AAA_.+_BBB$/) })
You can give use $('input', <context>)
to make the search more precise. See also here
I use to solve this with the class selectors which don't need to be unique.
This also has a positive effect on speed because no complex search is required Additionally you can use this for the different styling of different elements
eg
<elem id="1" class="aa">element type aa</elem>
<elem id="2" class="aa">element type aa</elem>
<elem id="3" class="aa bb">element type aa and bb</elem>
<elem id="4" class="bb">element type bb</elem>
Now you can simply use the class selector
$('.aa').click(function(){
console.log( 'clicked type aa #' + $(this).attr('id') );
});
$('.bb').click(function(){
console.log( 'clicked type bb #' + $(this).attr('id') );
});
最好只检查_BBB上的id结尾
$("[id$=_BBB]")
How about this :
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<input id="AAA_RandomString_BBB" type="text" />
<input id="AAA_RandomString_BBB_Start" type="text" />
<input id="AAA_RandomString_BBB_End" type="text" />
<script>
$(document).ready(function () {
debugger
var targetElement = $('input')
.filter(function () {
var el = this.id.match(/^AAA.*BBB$/g);
return el;
});
console.log(targetElement.val());
})
</script>
</body>
</html>
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.