Javascript 是否可以将.val与类一起使用?

Javascript 是否可以将.val与类一起使用?,javascript,jquery,Javascript,Jquery,我对编程相当陌生,我一直在做一些我认为很容易的事情!我正在创造一辆品牌、型号和年份的汽车。我正在查找用户在输入文本框中键入的内容的值,并将其打印在页面的顶部。我可以找到带有ID的值,但当我试图将其设置为类时,它不允许我将其打印出来。有人能解释一下吗?谢谢 这是我的HTML和JS: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https:

我对编程相当陌生,我一直在做一些我认为很容易的事情!我正在创造一辆品牌、型号和年份的汽车。我正在查找用户在输入文本框中键入的内容的值,并将其打印在页面的顶部。我可以找到带有ID的值,但当我试图将其设置为类时,它不允许我将其打印出来。有人能解释一下吗?谢谢

这是我的HTML和JS:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="carJquery.js"></script>
    <link rel="stylesheet" href="carjquerystylesheet.css">
    <title>Olivia's Car Challenge</title>
    <link href='https://fonts.googleapis.com/css?family=Ultra' rel='stylesheet' type='text/css'>
  </head>
  <body>
    <!--where your car make model and year will go-->
    <h3 id="carName">Your Car </h3></br>
    <h4 id="responseToUsersChangeInSpeed"></h4></br>
    <h4 id="currentSpeed"></h4>
    <!--we want a place for text entry for people to enter in their car info-->
    <label for="make" class="make">Enter Make</label>
    <input type="text" class="make" value="" name="make"/></br>
    <label for="model" class="model" >Enter Model</label>
    <input type="text" class="model" value="" name="model"/></br>
    <label for="year" class="year" >Enter Year</label>
    <input type="text" class="year" value="" name="year"/></br>
    <input id="createCarButton" type="button" value="Create My Car"/>

    <!--a button for increase speed-->
    <input id="accelerateButton" type="button" value="Accelerate"/>

    <!--a button for decrease speed-->
    <input id="brakeButton" type="button" value="Brake"/>

    <!--a button for the fluid increase to 70 and decrease back to 0-->
    <input id="fluidIncreaseDecreaseButton" type="button" value="Surprise!"/>

  </body>
</html>

奥利维亚的汽车挑战赛
你的车

输入Make
进入模型
进入年份
JS文件:

$(document).ready(function() {
    //allows us to change the speed of the car
      var speed = 0;
      var maxSpeed = 85;
      var brakeRate = Math.floor((Math.random()*6) + 5); //sets to a random rate between 5 and 10
      var accelerateRate = Math.floor((Math.random()*21) + 10); //sets to a random rate between 10 and 30

    //A function to create the car based on the user's input
    $("#createCarButton").click (function() {
      //Create a variable to hold a string of the user's input
      var nameOfCar = $(".make").val() + ", " + $(".model").val() + ", " + $(".year").val();
      //Change the carName header to reflect the user's nameOfCar
      $("#carName").html(nameOfCar);
      //updating the user with their speed
      $("#currentSpeed").html("Your current speed is: " + speed);
      //Hide the user input boxes after the car has been created
      $(".make").hide();
      $(".model").hide();
      $(".year").hide();
      $("#createCarButton").hide();
    });

    //function which runs when the user clicks on the "Accelerate" button
    $("#accelerateButton").click(function accelerate(){
      //If they've already hit their max speed, and they still try to accelerate...
      if (speed === maxSpeed){
        //...inform them that they can't
        $("#responseToUsersChangeInSpeed").html("You can't go any faster!!");
      }
      //Otherwise, if the rate of their acceleration is less than or equal to the difference between the maxSpeed, and their speed, allow them to accelerate
      else if (accelerateRate <= (maxSpeed - speed)){
        //increase their speed by the accelerateRate
        speed += accelerateRate;
        //tell them how fast they're going
        $("#currentSpeed").html("Your current speed is: " + speed);
      }
      //Otherwise, the accelerateRate would take them over the maxSpeed, so we only let them go as fast as the maxSpeed
      else {
        //change their speed to the maxSpeed
        speed = maxSpeed;
        //tell them they've hit the max speed
        $("#responseToUsersChangeInSpeed").html("You've hit your max speed of " + maxSpeed + ". Don't even try to go faster.");
        //tell them how fast they're going
        $("#currentSpeed").html("Your current speed is: " + speed);
      }
    });

    $("#brakeButton").click(function(){
      if (speed === 0) {
        $("#responseToUsersChangeInSpeed").html("You are already at a dead stop.");
      }
      else if(brakeRate <= speed) {
        speed -= brakeRate;
        //tell them how fast they're going
        $("#currentSpeed").html("Your current speed is: " + speed);
      }
      else {
        speed = 0;
        $("#responseToUsersChangeInSpeed").html("You've come to a complete stop.");
        $("#currentSpeed").html("Your current speed is: " + speed);
      }
    });

    $("#fluidIncreaseDecreaseButton").click(function(){
      maxSpeed = 70;
      while(speed < maxSpeed) {
        $("#accelerateButton").click();
        $("#currentSpeed").html("Your current speed is: " + speed);
        console.log(speed);
      };
      while(speed > 0) {
        $("#brakeButton").click();
        $("#currentSpeed").html("Your current speed is: " + speed);
        console.log(speed);
      };
      $("#brakeButton").click();
    });
});
$(文档).ready(函数(){
//允许我们改变汽车的速度
var速度=0;
var maxSpeed=85;
var brakeRate=Math.floor((Math.random()*6)+5);//设置为5到10之间的随机速率
var accelerateate=Math.floor((Math.random()*21)+10);//设置为10到30之间的随机速率
//根据用户输入创建汽车的功能
$(“#createCarButton”)。单击(函数(){
//创建一个变量来保存用户输入的字符串
var nameOfCar=$(“.make”).val()+,“+$(.model”).val()+,“+$(.year”).val();
//更改carName标题以反映用户的nameOfCar
$(“#carName”).html(nameOfCar);
//用他们的速度更新用户
$(“#currentSpeed”).html(“您当前的速度是:“+speed”);
//创建汽车后隐藏用户输入框
$(“.make”).hide();
$(“.model”).hide();
$(“.year”).hide();
$(“#createCarButton”).hide();
});
//当用户单击“加速”按钮时运行的功能
$(“#加速按钮”)。单击(函数加速(){
//如果他们已经达到了最高速度,他们仍然试图加速。。。
如果(速度===最大速度){
//…告诉他们他们不能
$(“#responseToUsersChangeInSpeed”).html(“你再也不能跑得更快了!!”;
}
//否则,如果它们的加速度小于或等于maxSpeed和它们的速度之间的差值,则允许它们加速
否则如果(加速0){
$(“#制动按钮”)。单击();
$(“#currentSpeed”).html(“您当前的速度是:“+speed”);
控制台日志(速度);
};
$(“#制动按钮”)。单击();
});
});

标签和输入都有“.make”类。因此,当您尝试使用$('.make')时,jQuery将返回一个数组(因为它使用类“.make”选择两个元素)


请尝试$('input.make').val()

问题是您为输入和标签指定了相同的类名。因此,jquery不知道使用哪一个。

$(“.make”).val()
将不会返回任何内容,因为您有两个元素带有标签和输入,并且由于标签在DOM中位于第一位。
$(“.make”).val()
将尝试获取标签的值

尝试将该代码更改为
$(“input.make”).val()
这将使用class=“make”获取输入值


对jQuery选择器的工作原理有很好的解释。

由于HTML代码包含多个具有所需类的元素,因此使用
$(“.make”)
选择具有类“make”的所有元素。它还通过与HTML中出现顺序相关的顺序来选择它们。因此,当HTML中的第一个“make”元素是“label”,第二个是“input”时,它们在jQuery选择结果中的顺序相同:
[,]

当您为jQuery选择结果调用
.val()
时,它将返回结果中第一个元素的值。而且,因为第一个元素是“label”,它不是表单输入(“输入”、“按钮”、“文本区域”或“选择”),所以
$(“.make”).val()返回空字符串

要准确地选择和使用“input”元素的值,您需要使用
$(“input.make”).val()
$(“input.model”).val()
,以及
$(“input.year”).val()
说明

此外,还可以选择具有名称的表单元素:
$('input[name=“make”])
甚至
$('[name=“make”])
。它将是这样的:

var nameOfCar = $('[name="make"]').val() + ", " + $('[name="model"]').val() + ", " + $('[name="year"]').val();
但我认为,更具可读性的变化是:

var nameOfCar = $("input.make").val() + ", " + $("input.model").val() + ", " + $("input.year").val();

因此,您的意思是这不起作用:
$(“.make”).val()
?您有两个元素具有make类,这两个元素中只有一个具有.val()方法(输入,而不是标签)。改为使用它获取值:$('input.make').val();型号和年份也一样。谢谢!我很感激你的详细解释,现在说得通了。我刚刚试了一下,效果很好@奥利维亚,我很高兴能帮上忙。另外,请考虑阅读关于堆栈溢出的答案的帮助文章: