views:

237

answers:

4

I have a situation where I should append html with jQuery. Within this html there is an a-tag with javascript as link.

How can I solve this?

$(".messages-wrapper").append('<li class="chat-wrapper"><a class="chat" href="javascript:openChat('http://domain.com/Messenger.aspx'"&gt;Chat öffnen<span></span><small>Chat öffnen</small></a></li>')

Thanks!!

+4  A: 

You can escape single or double quotes in a string with a backslash.

'... href="javascript:openChat(\'http...\')">...'
Joel Potter
+2  A: 

You just have to escape the apostrophes in the string using \':

$(".messages-wrapper")
.append('<li class="chat-wrapper"><a class="chat" href="javascript:openChat(\'http://domain.com/Messenger.aspx\'"&gt;Chat öffnen<span></span><small>Chat öffnen</small></a></li>');
Guffa
+2  A: 

You're probably having problems because of the quotes in the string. The single quotes are terminating the string early and causing a javascript error.

Consider, however, applying the hander at the same time that you append the html.

 var link = $('<li class="chat-wrapper"><a class="chat" href="http://domain.com/Messenger.aspx"&gt;Chat öffnen<span></span><small>Chat öffnen</small></a></li>')
            .find('a')
            .click( function() {
                 openChat($(this).attr('href'));
                 return false;
            });
 link.appendTo(".messages-wrapper");
tvanfosson
+1, will degrade gracefully if javascript is not enabled, though I'm guessing the chat page needs JS anyway.
Joel Potter
@Joel: A bit moot to consider how code created with Javascript would behave if Javascript was not enabled...
Guffa
@tvanfosson: You are missing the point completely. If Javascript isn't enabled, the code that creates the link doesn't execute.
Guffa
@Guffa, you are correct. However, I still discourage embedding javascript in markup, even javascript generated markup.
Joel Potter
@Guffa - you're right, of course, you caught me before my morning coffee and I responded without re-reading my answer. In my case what I usually do is simply put the HTML inline and add handlers later so I assumed that's how I had answered. If the chat page does require javascript, though, this would be a *better* way to add the HTML as it then wouldn't exist unless javascript were enabled.
tvanfosson
+1  A: 

Just use a nested append off of a created opject, to do the click action.

$('.messages-wrapper')
  .append(
    $('<li class="chat-wrapper" />")
      .append(
        $('<a class="chat" href="http://domain.com/Messenger.aspx"&gt;&lt;small&gt;Chat öffnen</small></a>')
          .click(function(){
            openChat(this.href);
            return false;
          })
      )
  );

This is easier to read the intention anyway, imho.

Tracker1
+1 for being very jQueryie
TehOne