开发者

jQuery append HTML with javascript link

开发者 https://www.devze.com 2022-12-26 12:18 出处:网络
I have a situation where I should append html with jQuery. Within this html there is an a-tag with javascript as 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.co开发者_高级运维m/Messenger.aspx'">Chat öffnen<span></span><small>Chat öffnen</small></a></li>')

Thanks!!


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

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


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");


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>');


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号