如何在document.writes中注入CSS?

时间:2014-02-27 07:21:15

标签: javascript jquery html css

我正在创建某种预订 - 评论。如何在此代码中进行一些设计和对齐。我试过把它放在div中,但仍然无效。我有什么方法可以做到这一点吗?

<html>
<head>

<style>
body{
    font-family:metro normal;
    font-size:30px;
} 

</style>

<script>

    // Called on body's `onload` event
    function init() {
            var SelectCountry = localStorage.getItem("SelectCountry");
            var SelectTime = localStorage.getItem("SelectTime");
    var datepicker = localStorage.getItem("datepicker");
        var Persons = localStorage.getItem("Persons");

            document.write("Branch: \r\n"  +SelectCountry);
        document.write(" \r\nTime: " +SelectTime);
        document.write(" \r\nDate: " +datepicker);

            if (Persons !== null){
             document.write(" \r\nPersons: " +Persons);

                }
        }


</script>
</head>    

<body onload = "init();">

</body>

2 个答案:

答案 0 :(得分:1)

这是因为您在文档就绪后调用了document.write(),这完全删除了当前文档。

所以删除onload处理程序和

function init() {
    var SelectCountry = localStorage.getItem("SelectCountry");
    var SelectTime = localStorage.getItem("SelectTime");
    var datepicker = localStorage.getItem("datepicker");
    var Persons = localStorage.getItem("Persons");

    //document.write('<style>body {color: red;}</style>');

    document.write("Branch: \r\n" + SelectCountry);
    document.write(" \r\nTime: " + SelectTime);
    document.write(" \r\nDate: " + datepicker);

    if (Persons !== null) {
        document.write(" \r\nPersons: " + Persons);

    }
}
init();

注意:尝试使用dom元素修改而不是像

那样使用document.write
// Called on body's `onload` event
function init() {
    var SelectCountry = localStorage.getItem("SelectCountry");
    var SelectTime = localStorage.getItem("SelectTime");
    var datepicker = localStorage.getItem("datepicker");
    var Persons = localStorage.getItem("Persons");

    var html = "Branch: \r\n" + SelectCountry;
    html += " \r\nTime: " + SelectTime;
    html += " \r\nDate: " + datepicker;

    if (Persons !== null) {
        html += " \r\nPersons: " + Persons;
    }

    document.body.innerHTML = html;
}

然后

<body onload = "init();">

答案 1 :(得分:0)

如果我理解正确,你不希望文本写在正文中,而是在特定的div ...中吗?

如果是,那么而不是

document.writy("text")

你可以使用这个Javascript

document.getElementById('idOfTheDiv').innerHTML="text"

或者,使用jQuery:

$("#idOfTheDiv").html("text")

希望它对你有所帮助。