jQuery-将html字符串附加到变量中的html字符串 [英] Jquery - appending html string to html string in variable

查看:101
本文介绍了jQuery-将html字符串附加到变量中的html字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个HTML字符串,然后使用额外的HTML和属性修改该HTML字符串,但是它不起作用.我在做什么错了?

I am trying to create an HTML string and then modify that HTML string with extra HTML and attributes but it's not working. What am I doing wrong?

$(document).ready(function(){
    $('body').on('click', 'button', function(){
        var thing     = '<div class="thing"></div>';
        var close     = '<a href="#" class="close">close</a>';

        $(thing).append(close);

        $('.canvas').append(thing);

        return false;
    });
});

在将字符串附加到DOM之前,我确实通过将字符串组合到一个变量中来使其工作,但这使我难以阅读.还有其他方法吗?

I did get it to work by combining the strings into one variable before appending them to the DOM but this makes what I'm doing harder to read. Is there any other way of doing this?

这是一个小提琴 .

Here is a fiddle.

推荐答案

更新了小提琴 .

Updated fiddle.

您必须将表达式$(thing).append(close);的返回值分配给变量thing,例如:

You have to assign the return of this expression $(thing).append(close); to the variable thing like:

thing = $(thing).append(close);

否则变量将始终保留默认字符串<div class="thing"></div>作为值.

Else the variable will always hold the default string <div class="thing"></div> as value.

希望这会有所帮助.

$(document).ready(function(){
  $('body').on('click', 'button', function(){
    var thing	  = '<div class="thing"></div>';
    var close	  = '<a href="#" class="close">close</a>';

    $('.canvas').append( $(thing).append(close) );

    return false;
  });
});

.thing {
  width: 50px;
  height: 50px;
  background: red;
}

.close {
  background: blue;
  color: white;
}

.canvas {
  border: 1px solid black;
  width: 500px;
  height: 500px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add Thing</button>
<div class="canvas"></div>

这篇关于jQuery-将html字符串附加到变量中的html字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆