jQuery UI对话框文本有换行符选项吗?

Does jQuery UI dialog box text have a newline option?

本文关键字:选项 换行符 UI 对话框 文本 jQuery      更新时间:2023-09-26

我正在制作一个网站,使用口袋妖怪的数据,并试图执行一个对话框。我试过在文本中使用JS换行符:

function alertBox(monster) {
    $("#dialog").dialog();
    $("#dialog").dialog("option", "title", monster);
    $("#dialog").text("Height: "  + pokemon.height[monster] + "'n" +
                      "Weight: " + pokemon.weight[monster]);
}

…我也试过使用html换行标签:

function alertBox(monster) {
    $("#dialog").dialog();
    $("#dialog").dialog("option", "title", monster);
    $("#dialog").text("Height: "  + pokemon.height[monster] + "<'br>" +
                      "Weight: " + pokemon.weight[monster]);
}

但是似乎都没有返回我正在寻找的换行符效果!JS换行符只是作为一个空格,html换行符只是连接到字符串。是否有一种方法来强制在对话框文本换行?

jQuery .text()函数自动转义HTML实体,因此您的<br />标记不再被解释为HTML,而是被转换为转义文本。

为了防止这种HTML转义,您需要使用.html()而不是.text()来设置内容:

function alertBox(monster) {
    $("#dialog").dialog();
    $("#dialog").dialog("option", "title", monster);
    $("#dialog").html("Height: "  + pokemon.height[monster] + "<br />" +
                      "Weight: " + pokemon.weight[monster]);
}

考虑添加

$("#dialog").css("white-space","pre-wrap");

这将使'n显着,它将呈现这样。

或者,考虑使用一些实际的HTML。例如,你的对话框可以是:
$("#dialog").html("<ul>" +
    "<li><b>Height:</b> "+pokemon.height[monster]+"</li>" +
    "<li><b>Weight:</b> "+pokemon.weight[monster]+"</li>" +
"</ul>");

对于更复杂的布局,我建议使用模板系统,而不是将HTML硬编码到JavaScript中。

希望这将有助于了解如何文本()val()和html()的工作

$(document).ready(function () {
    $("#dialog").html("Height: " + 11 + "<br>" +
        "Weight: " + 22);
    $("#dialog2").val("Height: " + 11 + "'n" +
        "Weight: " + 22);
    $("#dialog3").text("Height: " + 11 + "'n" +
        "Weight: " + 22);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dialog"></div>
<textarea rows="5" cols="20" name="text" id="dialog2"></textarea>
<textarea rows="5" cols="20" name="text" id="dialog3"></textarea>