javascript 使用 jQuery 更改 h-text

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17098929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:05:01  来源:igfitidea点击:

Changing h- text with jQuery

javascriptjqueryhtml

提问by user2484181

I want to change the text of a h2. If I use alert, it shows undefined with .html and .val, so, wouldn't it be something like this?:

我想更改 h2 的文本。如果我使用警报,它会用 .html 和 .val 显示未定义,所以,它不会是这样的吗?:

$("#h2Id").text("new text");

$("#h2Id").text("new text");

It doesn't work, though. Thanks in advance.

但是,它不起作用。提前致谢。

edit: the html is plain simple, as I'm trying to understand why it doesn't work.

编辑:html 很简单,因为我试图理解为什么它不起作用。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="jquery.js"></script>    
    <link href="css/estilos.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="testingStuff.js"></script>
</head>
<body>
    <h2 id="question"> ASD </h2>
</body>

回答by Frambot

  1. Make sure jQuery is loaded.

  2. Use the document-ready incantation to let your script wait until the DOM is ready.

    $(function() {
        $("#h2Id").text("new text");
    });
    
  3. http://jsfiddle.netis a wonderful resource for quickly mocking up pages and finding problems.

  1. 确保 jQuery 已加载。

  2. 使用 document-ready 咒语让您的脚本等待 DOM 准备就绪。

    $(function() {
        $("#h2Id").text("new text");
    });
    
  3. http://jsfiddle.net是快速模拟页面和查找问题的绝佳资源。

回答by Mr. Polywhirl

http://jsfiddle.net/4jmEx/

http://jsfiddle.net/4jmEx/

<span id="h2Id">Foo</span>
$('#h2Id').text('Bar');