使用JS/JQ单击按钮时更改DIV文本

Change DIV text when a button is clicked using JS/JQ

本文关键字:DIV 文本 按钮 JS JQ 单击 使用      更新时间:2023-09-26

Caveat:第二次海报,新手开发者。我刚刚完成了CodeSchool的"TryJQuery",所以现在我正在尝试使用HTML/CSS/JS/JQ的混合构建一个小测验。请原谅任何混乱或偏离规范的行为。我希望能尽快赶到那里!

当单击按钮时,我正试图更改类div.questions中的文本,但什么也没发生。到目前为止,我只在CodeSchool上做过这件事,所以这是我第一次尝试自己构建它。据我所知,我的代码是正确的,但像"script-src"这样基本的东西是不正确的。我目前使用的是.text(new-text方法,也许我应该使用类似.html(new-text)的方法

编辑:澄清-我的问题不是这在JSFiddle中不起作用。下面的评论说明了为什么会这样,所以谢谢。然而,我真正的问题是,在将文档本地加载到我的浏览器时,这不起作用。我正在使用Sublime Edit。谢谢

JSFiddle:http://jsfiddle.net/Ever/jvNf8/

HTML:

<!DOCTYPE html>
<html>
<head>
    <link type="text/css" rel="stylesheet" href="stylesheet.css"/>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="jquery.min.js"></script>
    <title>Tim's JS Quizlet!</title>
</head>
<body>
    <h2>JS and JQuery Quiz</h2>
    <div class="intro">
    Welcome! When the button at the bottom is clicked, the question in the box below 
will change to the next question, and the answer choices below will change to the 
respective choices.
    <br>
    </div>
    <br>
    <div class="questions">Ready?</div>
    <br>
    <input type="radio" id="radio1" name="radios"> Yes</br>
    <input type="radio" id="radio2" name="radios"> No</br>
    <input type="radio" id="radio3" name="radios"> Wat</br>
    </br>
    <button>Submit</button>
</body>

CSS:

div.intro{
font-weight: bold;
width: 50%;
}
div.questions{
width: 500px;
height: 100px;
border: 1px solid black;
padding: 5px;
}

JS:

$(document).ready(function(){ 
$('button').on('click', function(){
    $('.questions').text("What's your favorite color?");
    });
});

您需要从jsFiddle的Frameworks and Extensions选项卡中包含jQuery,它就可以工作了。

更新的Fiddle

包含jQuery库并将脚本更改为:

$(document).ready(function(){ 
    $('button').click(function(){
        $('.questions').html("What's your favorite color?");
    });
});

FIDDLE

使用

button:action
{
//<how you want it changed here>//
} 

在css中。

它工作得很好。

问题是您使用的是JSFiddle,而您还没有包含jQuery。您可以在左侧的Frameworks & Extensions平移中执行此操作。

将代码放在"head"标签中:

 <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
 <script>
    $(document).ready(function(){ 
       $('button').click(function(){
         $('.questions').html("What's your favorite color?");
       });
    });
 </script>

在使用jquery函数之前,您需要提供jquerylib的引用。