【问题标题】:Changing content of class using Javascript使用 Javascript 更改课程内容
【发布时间】:2014-02-16 15:23:12
【问题描述】:

我开始在 W3schools 中阅读 JavaScript,并在他们提供的示例中测试/更改了一些内容,以便我可以看到什么在做什么,但还没有设法识别语法。

下面是修改p标签内容的原代码,link改成它。

<p id="demo">
    JavaScript can change the content of an HTML element.
</p>

<script>
function myFunction()
{
    x = document.getElementById("demo");  // Find the element
    x.innerHTML = "Hello JavaScript!";    // Change the content
}
</script>

<button type="button" onclick="myFunction()">Click Me!</button>

我想知道如何更改同一个类的内容,但失败了,因为您可以看到下面的示例不起作用。 Fiddle of code below.

<p class="demo">
    JavaScript can change the content of an HTML element.
</p>

<p class="demo">Yolo</p>

<script>
function myFunction()
{
    x = document.getElementsByClassName("demo");  // Find the element
    x.innerHTML = "Hello JavaScript!";    // Change the content
}
</script>

<button type="button" onclick="myFunction()">Click Me!</button>

如果您能告诉我如何 ^^" 并帮助我理解,“getElementById”是一个可以是其他变量还是命令?

【问题讨论】:

    标签: javascript html onclick tags


    【解决方案1】:

    您的 x - 是元素数组。尝试使用循环:

    <body>
    
    <p class="demo">JavaScript can change the content of an HTML element.</p>    
    <p class="demo">Yolo</p>   
    
    <button type="button" onclick="myFunction()">Click Me!</button>
    
    <script>        
    function myFunction()
    {
    x=document.getElementsByClassName("demo");  // Find the elements
        for(var i = 0; i < x.length; i++){
        x[i].innerText="Hello JavaScript!";    // Change the content
        }
    
    }
    
    </script>
    </body>
    

    FIDDLE

    【讨论】:

    • 在小提琴中你有一个额外的行 "console.log(x)" D:: 这是什么?
    • 它只是在控制台中显示一条消息。
    • 我使用它只是为了确保我所做的一切都是正确的
    • 哦,好吧,我认为这很奇怪,因为没有它它可以正常工作。谢谢!
    【解决方案2】:

    注意使用时的方式:

    x=document.getElementsByClassName("demo"); 
    

    它是元素而不是元素。这是因为它返回 一个数组 一个包含一个特定类名的所有元素的 HTMLCollection。为了解决这个问题,您可以选择数组中的第一个元素

    x=document.getElementsByClassName("demo")[0];
    

    【讨论】:

    • 我读了你的答案 4 次然后我就理解了数组的东西! (我从 Pascal 想到了数组)。测试它并工作,[0] 更改了第一个文本,[1] 更改了第二个。谢谢!循环的东西是我想要的
    • var x=document.getElementsByClassName("demo")[0].innerHTML;但我想使用 jquery 访问它,那么我怎样才能获得变量 x
    【解决方案3】:

    在 Javascript 中使用 jQuery 更容易

    看这个例子: http://jsfiddle.net/37jq9/3/

    如果你使用 jquery 而不是调用

    x=document.getElementsByClassName("demo");
    

    你可以使用

    x = $('.demo');
    

    但你可以像这样调用函数:

    $(document).ready(function(){
        $('button').click(function(){
            $('.demo').text('Hello Javascript');
        })   
    })
    

    【讨论】:

    • “我在 W3schools 开始阅读 JavaScript” - Harlequin 应该首先学习 JavaScript。
    • "在 Java 中更容易使用 jQuery"? - 什么? Java != JavaScript,理想情况下应该在开发依赖任何库之前学习 JavaScript。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2021-01-05
    • 2013-11-02
    • 2023-03-28
    • 2020-12-30
    • 2018-04-05
    相关资源
    最近更新 更多