patternjavascriptMinor
Replacing text in an array
Viewed 0 times
arraytextreplacing
Problem
I have this piece of code to replace current text inside an array of html divs with values coming from a JSON file:
I'd like to make it "dynamic": if I'd have 100 values, I don't want to copy/paste it 100 times.
Maybe it would be better creating an array "CameraTypeLabel" in the JSON string ?
EDIT: Fixed the selector, it was a typo.
Thanks!
$.each($('.something'), function(){
if($(this).text()=="1"){
$(this).html(jsondata.CameraTypeLabel1);
}else if($(this).text()=="2"){
$(this).html(jsondata.CameraTypeLabel2);
}
});I'd like to make it "dynamic": if I'd have 100 values, I don't want to copy/paste it 100 times.
Maybe it would be better creating an array "CameraTypeLabel" in the JSON string ?
EDIT: Fixed the selector, it was a typo.
Thanks!
Solution
jQuery's
You can use bracket notation to access the key in your
Note:
If all you want to do is update the text, you can pass a function to
.html() method can take a callback function - it'll be called for every element in the collection - and will use the returned value to set the element's html.You can use bracket notation to access the key in your
jsondata, so that you can dynamically get to the key you want with the string in the brackets:$('.something').html(function () {
return jsondata[ 'CameraTypeLabel' + $.text(this) ];
});Note:
$.text(this) is the same as $(this).text(), just a bit faster; it doesn't create a new jQuery object at every step in the loop.If all you want to do is update the text, you can pass a function to
.text() itself:$('.something').text(function (i, oldText) {
return jsondata[ 'CameraTypeLabel' + oldText ];
});Code Snippets
$('.something').html(function () {
return jsondata[ 'CameraTypeLabel' + $.text(this) ];
});$('.something').text(function (i, oldText) {
return jsondata[ 'CameraTypeLabel' + oldText ];
});Context
StackExchange Code Review Q#21440, answer score: 3
Revisions (0)
No revisions yet.