Reputation: 19315
In Ruby you can use string interpolation like so:
text = "This is visit number #{numVisits} to this website"
This bypasses the need for explicit concatenation.
I'm working with jQuery and have a bit like this:
$(document).ready(function(){
$("a.ajax").click(function(event){
$("#content").load("data.html this.getClass");
});
});
The behavior I want is "click on <a class="ajax" id="schedule"></a>
and the content
div
on the current page is replaced by the schedule
div
from data.html
. If I manually write in
load("data.html #test");
that works, but I want the script to load the DIV with the ID value of the anchor clicked. Any help would be swell!
Example Page: http://www.mariahandalex.info/stack/
Upvotes: 13
Views: 16787
Reputation: 22787
in es6 this is possible
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings
`string text ${expression} string text`
Upvotes: 5
Reputation: 4930
This has changed.
As of 2015 there is now a better way: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings
Bringing to JS what many languages like Ruby and PHP have enjoyed already.
For example, in my jQuery driven page I use:
$('#myModalLabel').html(`Show GRAPH of : ${fundCode}-${funcCode}`);
Which safely renders in my updated Firefox and Chrome as:
Show GRAPH of : AIP001-_sma
Note the use of backticks surrounding the string param in .html(....)
Upvotes: 17
Reputation: 33653
You cannot embed javascript code inside a string, but you can concatenate a string to an object using '+' like so
$('#content').load('data.html #' + $(this).getClass());
About embedding code in a string, I don't think it has a name. Groovy calls those strings "Gstring"s, and ruby calls those 'Expression substitution in strings'. I'm not sure it has a standard name.
Upvotes: 6
Reputation: 655795
Try this:
$(document).ready(function(){
$("a.ajax").each(function(){
var obj = $(this);
obj.click(function(event){
alert(obj.attr('id'));
});
});
});
Upvotes: 2
Reputation: 189555
Javascript doesn't parse string literals looking for replacement markers like Ruby or PHP does. You will have to use concatenation.
Upvotes: 5