问题 jQuery UI对话框文本是否有换行选项?


我正在使用来自Pokemon的数据创建一个网站并尝试执行一个对话框。我试过在文中使用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换行标记只是连接到字符串。有没有办法在对话框文本中强制换行?


3141
2017-09-07 19:38


起源

为什么“<br>”到处都是? - Amit
使用 .html() 同 <br /> 代替 .text()。 - j08691
与使用对话框无关...这就是html的工作方式。 - charlietfl


答案:


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]);
}

8
2017-09-07 20:02





考虑添加:

$("#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中。


1
2017-09-07 20:01





希望有助于了解text()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>


1
2017-09-07 20:17