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

标签 javascript jquery

我对编程还很陌生,并且被困在我认为很容易的事情上!我正在创建一辆带有品牌、型号和年份的汽车。我正在查找用户在输入文本框中键入的内容的值并将其打印在页面的头部。我能够找到带有 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>

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();
    });
});

最佳答案

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

当您调用 .val() 时对于 jQuery 选择结果,它返回结果中第一个元素的值。而且,因为第一个元素是“label”,它不是表单输入(“input”、“button”、“textarea”或“select”),$(".make").val()返回空字符串。

要选择和使用恰好“输入”元素的值,您需要使用 $("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();

关于javascript - 是否可以将 .val 与类一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35962525/

相关文章:

javascript - 如何从父级上取消div的钩子(Hook)然后将其钩回来?

javascript - Angular 数据表 ng-repeat 不起作用

javascript - 在 infiniteHits 小部件上触发 showMore (Algolia istantsearch.js)

javascript - jQuery Mobile 在页面转换时闪烁

javascript - 无法访问 Javascript 标记内的 Rails 变量

javascript - NPM模块导入时抛出错误

asp.net - 哪个 Javascript 历史回溯实现是最好的?

javascript - jquery 序列化返回一个空字符串

javascript - 如何在 jQuery 上重写它

javascript - 使用javascript计算耗时