且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery-将html字符串附加到变量中的html字符串

更新时间:2021-10-19 04:20:35

更新了小提琴 .

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>