如何使用jQuery追加html?

时间:2014-02-13 13:42:31

标签: jquery html

我一直在尝试将html数据从html文件附加到html页面。它似乎很简单,但它不起作用!你能救我吗?

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        var theCitiesList="<?php echo htmlentities(file_get_contents("cityOptions.html")); ?>";
        $("select#chooseCity").html(theCitiesList);                 
    });
</script>
</head>
<body> 
    <FORM id="searchForm">
        <h2>Selecione uma cidade: </h2>            
        <select id="chooseCity"></select>
    </FORM>
</body>  
</html>     

cityOptions.html基本上是一长串城市,例如:

        <option value="" selected></option>
        <option value="1">California</option>
        <option value="2">New York</option>

3 个答案:

答案 0 :(得分:2)

您可以使用JQuery .load()之类的;

$("select#chooseCity").load("cityOptions.html");

这会将cityOptions.html加载到指定的html区域

答案 1 :(得分:1)

.load()是$ .get()的快捷方式:

$(document).ready(function() {
    $.get('cityOptions.html', function(data) {
        $('#chooseCity').html(data);
    });            
});

答案 2 :(得分:0)

cityOptions.html有换行符\n。替换它有帮助。

<html>
<head>       
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var theCitiesList='<?php echo str_replace(array("\r\n", "\n", "\r"), "",file_get_contents("cityOptions.html"));  ?>';
            $("select#chooseCity").html(theCitiesList);                 
        });
    </script>
</head>
<body>
    <form id="searchForm">
        <h2>Selecione uma cidade: </h2>            
        <select id="chooseCity">

        </select>
    </form>
 </body>