奇怪的JQuery追加未完成DIV


Strange JQuery Append Not Completing DIVs

我在Jquery附加功能方面遇到了一些问题。我想在PHP while循环中有一个DIV,所以我做了这段代码,并调用了开始的DIV标记,但结束的DIV标记没有注册到它的开始标记:

$('.class').append('<div class='"class_name'">');
'' While Loop
$('.class').append('</div>');

jQuery只追加完整的元素,如果jQuery不自动关闭,就无法追加打开的div标记。请尝试构建一个html字符串,然后追加该字符串。

var strOutput = "<div class='class_name'>";
// replace this with php loop: for (var i = 1; i < 10; i++) {
  strOutput += i;
// replace this with php loop: }
strOutput += "</div>";
$(".class").append(strOutput);

更新
假设您执行了phpwhile循环并生成了一个名为$strOutput的变量:

$strOutput = "<div class='class_name'>some text here</div>";

将其添加到您的javascript中,如下所示:

echo "$('.class').append('$strOutput');";

另一次更新

从字里行间读出来!那只是一个例子。。。构建一个字符串,然后回显它。

$strOutput = "<div class='class_name'>";
// within your while loop...
$strOutput = $strOutput."somevalue";
// now after your while loop...
$strOutput = $strOutput."</div>";
echo "$('.class').append('$strOutput');";

为什么不把while循环的输出放在一个变量中,然后把它附加到div。

更新

var output = //the output from the while loop

$('.class').append('<div class='"class_name'"></div>').append(output);

var div = $('<div class='"class_name'"></div>').append(output);    
$('.class').append(div);

您可以将while循环中的代码保存到一个变量中,然后在jquery append调用中回显它。

正如Kevin B在上面所说,jQuery只附加完整的元素,所以这样做:

<?php
//while loop (save whatever you'd echo/output to a var
?>
$('.class').append('<div class="class_name"><?=$output_from_while_loop?></div>');