m4mpfi
m4mpfi

Reputation: 1

jQuery append HTML with javascript link

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'">Chat öffnen<span></span><small>Chat öffnen</small></a></li>')

Thanks!!

Upvotes: 0

Views: 5396

Answers (4)

Tracker1
Tracker1

Reputation: 19344

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"><small>Chat öffnen</small></a>')
          .click(function(){
            openChat(this.href);
            return false;
          })
      )
  );

This is easier to read the intention anyway, imho.

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532765

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">Chat öffnen<span></span><small>Chat öffnen</small></a></li>')
            .find('a')
            .click( function() {
                 openChat($(this).attr('href'));
                 return false;
            });
 link.appendTo(".messages-wrapper");

Upvotes: 3

Guffa
Guffa

Reputation: 700910

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\'">Chat öffnen<span></span><small>Chat öffnen</small></a></li>');

Upvotes: 2

Joel
Joel

Reputation: 19378

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

'... href="javascript:openChat(\'http...\')">...'

Upvotes: 4

Related Questions