Friday, May 6, 2011

How can I "escape" quotes in javascript?

I don't know if "escaping" is the right word (please tell me what the right word/phrase is) but in Ruby you can say something like

text = "This is visit number #{numVisits} to this website"

so you can skip concatenation etc.

I'm working in 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/

From stackoverflow
  • Try this:

    $(document).ready(function(){
        $("a.ajax").each(function(){
            var obj = $(this);
            obj.click(function(event){
               alert(obj.attr('id'));
            });
        });
    });
    
    Gumbo : @Alex Mcp: Take a look at it now.
    geowa4 : '#' + this.getClass()? you probably meant '.'
    Alex Mcp : But that will append the Class of the "#content" div. That is where the data is getting shuttled in and out of. I need to find a way to tack on the "ID" attribute of the link that was clicked, because that will identify what gets pulled out of the external page.
    Gumbo : It should work now.
    Gumbo : I forgot that it’s an jQuery object that gets returned. It works now.
    Alex Mcp : I put an example page up. This is so strange, it's only returning the id value for the first in the list of links. Maybe the list is somehow the object, and it thinks it only has one ID? I'm a bit beyond my knowledge here... Thanks so much.
  • Javascript doesn't parse string literals looking for replacement markers like Ruby or PHP does. You will have to use concatenation.

  • 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.

    strager : I think you mean $(this).getClass() or maybe this.className.

0 comments:

Post a Comment