javascript - 将 Div 替换为内容

标签 javascript jquery

我是 javascript/jquery 的新手,我忽略了一些基本的东西。我想通过调用函数用一些文本替换 div 的内容。我尝试过的每件事绝对都失败了。

http://jsfiddle.net/spuder/dTGBy/

html

<body>
<div id=test>

</div>
</body>

脚本

$(document).ready( function()  {

   getTest();

}



function getTest() {
    $("#test").html("Hello World");
    //$('#test').replaceWith('<h2>New heading</h2>');
    //$("#test").attr("text","http://www.w3schools.com/jquery");
    //$("#test").attr("href","http://www.w3schools.com/jquery");
    //$("#test").html("New text");
    //$(".test").html("New text");
    //$("test")html.("New text");
    //$("test").update("New text");
    //document.getElementById("testSpan").innerHTML = "42";
    // $("#test").html("<b>Hello world!</b>"); 
}

//This is supposed to be super easy ^

//http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_dom_html_set
//http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_dom_attr_set
//http://www.willmaster.com/library/web-development/replace-div-content.php
//http://api.jquery.com/replaceWith/

最佳答案

好吧,你犯的错误:

  • JsFiddle 中未包含 jQuery
  • 错误地结束了您的document.ready
  • 忘记了 div id 周围的引号

JS:

$(document).ready(function(){
   getTest();
});



function getTest() {
    $('#test').replaceWith('<h2>New heading</h2>');
    //$("#test").attr("text","http://www.w3schools.com/jquery");
    //$("#test").attr("href","http://www.w3schools.com/jquery");
    //$("#test").html("New text");
    //$(".test").html("New text");
    //$("test")html.("New text");
    //$("test").update("New text");
    //document.getElementById("testSpan").innerHTML = "42";
    // $("#test").html("<b>Hello world!</b>"); 
}

HTML:

<div id="test">

</div>

fiddle http://jsfiddle.net/ajp36/1/

关于javascript - 将 Div 替换为内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15732537/

相关文章:

java - 具有 RESTful 内容提供商的动态网页

php - 每 5 秒用 jQuery/Ajax 刷新一个表

jquery - 使用 jQuery 计算元素的不透明度

javascript - 在同一端口上运行单独的 ASP.NET 项目

javascript - 将字符串从 javascript 发送到 php(在同一文件中)

javascript - 如何使用 javaScript/JQuery/Hibernate/Spring 在 jsGrid 中显示来自数据库的图像?

javascript - 将选定的行从 html 表加载到数组

javascript - 变音符号的正则表达式

javascript - 拖放和缩放图像,但用户上传的图片不可拖动和调整大小

jquery - 如何打开一个与 DIV 中所有元素的宽度完全相同的 JQuery 模式对话框?