可以在类中使用.val吗?

时间:2022-03-26 20:27:13

I am fairly new to programming and am stuck on something that I thought would be easy! I am creating a car with the make, model, and year. I am finding the value of what the user types into the input text box and printing it on the head of the page. I am able to find the value with an ID but when I try to make it a class, it does not allow me to print it out. Can anyone shed some light on this? Thank you!!

我对编程很新,而且我坚持做一些我认为很容易的事情!我正在制作一辆带有品牌,型号和年份的汽车。我发现用户在输入文本框中键入的值并将其打印在页面的头部。我能够找到带有ID的值,但是当我尝试将其设为类时,它不允许我将其打印出来。任何人都可以对此有所了解吗?谢谢!!

Here is my HTML and my JS:

这是我的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 FILE:

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

4 个解决方案

#1


0  

Problem is that you are assigning same class name to input and label. So, jquery does not know which one to use

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

#2


0  

$(".make").val() will not return anything because you have 2 elements with class="make" a label and input, and since the label came first in the DOM $(".make").val() will try to get the value of the label.

$(“。make”)。val()不会返回任何内容,因为你有2个元素,其中class =“make”是一个标签和输入,并且因为标签首先出现在DOM $(“。make”)。val( )将尝试获得标签的价值。

Try change that code to $("input.make").val() this will get the value of the input with class="make"

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

http://www.w3schools.com/jquery/jquery_ref_selectors.asp has good explanation of how the jQuery selectors work.

http://www.w3schools.com/jquery/jquery_ref_selectors.asp很好地解释了jQuery选择器的工作原理。

#3


0  

Since your HTML code contains more than one element with needed class, using $(".make") selects all elements having class "make". It also selects them with ordering related to the appearing order in the HTML. So when your first "make" element in HTML is "label" and the second is "input", they will have the same ordering inside jQuery selection result: [<label>, <input>]

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

When you call .val() for jQuery selection result, it returns value of first element in the result. And, because the first element is "label", which is not a form input (either "input", "button", "textarea", or "select"), the $(".make").val() returns empty string.

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

For selecting and using value of exactly "input" element, you need to use $("input.make").val(), $("input.model").val(), and $("input.year").val() instructions.

要选择和使用完全“input”元素的值,您需要使用$(“input.make”)。val(),$(“input.model”)。val()和$(“input.year” ).val()指令。

Also, it's possible to select form elements with their names: $('input[name="make"]') or even $('[name="make"]'). It will be something like this:

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

var nameOfCar = $('[name="make"]').val() + ", " + $('[name="model"]').val() + ", " + $('[name="year"]').val();

But, I think, more readable variation is:

但是,我认为,更易读的变化是:

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

#4


-1  

Both your label and input has the class ".make". So when you try to use $('.make') jQuery will return an array (as it selects both elements with the class ".make").

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

Try $('input.make').val().

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

#1


0  

Problem is that you are assigning same class name to input and label. So, jquery does not know which one to use

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

#2


0  

$(".make").val() will not return anything because you have 2 elements with class="make" a label and input, and since the label came first in the DOM $(".make").val() will try to get the value of the label.

$(“。make”)。val()不会返回任何内容,因为你有2个元素,其中class =“make”是一个标签和输入,并且因为标签首先出现在DOM $(“。make”)。val( )将尝试获得标签的价值。

Try change that code to $("input.make").val() this will get the value of the input with class="make"

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

http://www.w3schools.com/jquery/jquery_ref_selectors.asp has good explanation of how the jQuery selectors work.

http://www.w3schools.com/jquery/jquery_ref_selectors.asp很好地解释了jQuery选择器的工作原理。

#3


0  

Since your HTML code contains more than one element with needed class, using $(".make") selects all elements having class "make". It also selects them with ordering related to the appearing order in the HTML. So when your first "make" element in HTML is "label" and the second is "input", they will have the same ordering inside jQuery selection result: [<label>, <input>]

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

When you call .val() for jQuery selection result, it returns value of first element in the result. And, because the first element is "label", which is not a form input (either "input", "button", "textarea", or "select"), the $(".make").val() returns empty string.

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

For selecting and using value of exactly "input" element, you need to use $("input.make").val(), $("input.model").val(), and $("input.year").val() instructions.

要选择和使用完全“input”元素的值,您需要使用$(“input.make”)。val(),$(“input.model”)。val()和$(“input.year” ).val()指令。

Also, it's possible to select form elements with their names: $('input[name="make"]') or even $('[name="make"]'). It will be something like this:

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

var nameOfCar = $('[name="make"]').val() + ", " + $('[name="model"]').val() + ", " + $('[name="year"]').val();

But, I think, more readable variation is:

但是,我认为,更易读的变化是:

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

#4


-1  

Both your label and input has the class ".make". So when you try to use $('.make') jQuery will return an array (as it selects both elements with the class ".make").

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

Try $('input.make').val().

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