将 .attr 添加到调用时不起作用的按钮

Add .attr to button not working when called

不确定我是否正确格式化了问题。已手动添加 "data-next" 并在适当的时候更改,但仍未更改。已将其缩小到 "showNext" 函数。

我的 objective 是根据用户输入的汽车数量迭代有关汽车的问题。起初我在考虑循环,但这似乎是一种更简洁的方法。我是新来的,所以我可能会离开。

我的问题是,虽然它确实迭代了正确的次数,并且 chrome 表明它选择那个按钮作为我想要的 "this" 变量,出于某种原因它没有添加属性。那行代码触发了,我没有收到任何错误,但什么也没有发生。

我试过使用按钮的确切 ID,将 "this" 定义为变量(即:var el = 按钮的 id)和其他一些我现在不记得的东西。没有任何效果。我在其他地方也使用过相同类型的命令,效果很好。

其余代码工作正常,它确实循环了正确的次数,但它不会添加 attr。任何帮助将不胜感激。如果我遗漏了什么,请告诉我。谢谢!

这是JS:

$(document).ready(function () {

 // hide all 'hideFirst' elements, except the first one:
$('.hideFirst:not(:first)').hide();

// Method used to show/hide elements :
function showNext(el) {
    // check if element has a 'data-next' attribute:
    if (el.data('next')) {
        // hide all elements with 'hideFirst' class:
        $('.hideFirst').hide();
        // show 'Back' button:
        $('#backButton').show();
        // show the element which id has been stored in 'data-next' attribute:
        $(el.data('next')).show();
        // push the parent element ('.hideFirst') into path array:
        path.push(el.closest('.hideFirst'));
    }
}

    //Logs the number of cars in the household
$("#carAmount").click(function () {
    numberOfCars = parseInt(document.getElementById("vehicleAmount").value);
    showNext($(this));
});

//allow user to chose the type of car they drive
$("#carType").change(function () {

    carChoice = $("#carType").val();
    $("#carType").attr("data-next", "#" + carChoice);
    showNext($(this));

});

//Decides whether the user has more cars to ask about
    $(".carBtn").click(function () {
        carCount++;
        //asks about other cars
        if (carCount < numberOfCars) {
            $(this).attr('data-next', '#vehicleType');
            $('#carType').prop('selectedIndex', 0);
        }
            //moves on to the next category
        else {
            $(this).attr('data-next', '#transportation');
        }
        showNext($(this));
    });
});

这里是 HTML:

<div>
<form>
                <div class="hideFirst" id="vehicleCount">
                <label for="vehicleAmount">How many vehicles are there in your household?</label>
                <input type="text" id="vehicleAmount" />
                <button type="button" id="carAmount" data-next="#vehicleType" class="my-btn btnFoot"><i class="icon-footprint-right-d"></i></button>
            </div>

            <div class="hideFirst" id="vehicleType">
                <label for="carType">What kind of car do you drive?</label>
                <select id="carType">
                    <option disabled selected>--Choose One--</option>
                    <option value="gas">Gasoline</option>
                    <option value="diesel">Diesel</option>
                    <option value="cng">Natural gas</option>
                    <option value="hybrid">Hybrid</option>
                    <option value="elec">Electric</option>
                    <option value="hydrogen">Fuel Cell/Hydrogen</option>
                </select>
            </div>

            <div class="hideFirst" id="gas">
                <label for="fuelType">What type of fuel do you normally use??</label>
                <select id="gasType">
                    <option disabled selected>--Choose One--</option>
                    <option value="e10">e10 (regular unleaded)</option>
                    <option value="e85">e85</option>
                </select>
            </div>

            <div class="hideFirst" id="diesel">
                <label for="carType">What type of diesel fuel do you normally use?</label>
                <select id="dieselType" name="heatSource">
                    <option disabled selected>--Choose One--</option>
                    <option value="num5">Regular Diesel</option>
                    <option value="b10">B10 Biodiesel</option>
                    <option value="b100">B100 Biodiesel</option>
                </select>
            </div>

            <div class="hideFirst" id="cng">
                <label for="carCng">How much natural gas do you put in your car every month?</label>
                <input type="text" id="carCng" />
                <button type="button" id="propaneBill" class="carBtn btnFoot"><i class="icon-footprint-right-d"></i></button>
            </div>

            <div class="hideFirst" id="hybrid">
                <label for="carType">What kind of car do you drive?</label>
                <select id="carType" name="heatSource">
                    <option disabled selected>--Choose One--</option>
                    <option value="gas">Gasoline</option>
                    <option value="diesel">Diesel</option>
                    <option value="cng">Natural gas</option>
                    <option value="hybrid">Hybrid</option>
                    <option value="elec">Electric</option>
                    <option value="hydrogen">Fuel Cell/Hydrogen</option>
                </select>
            </div>

            <div class="hideFirst" id="elec">
                <label for="carElec">How many miles do you drive every month?</label>
                <input type="text" id="carElec" />
                <button type="button" id="elecMiles" class="carBtn btnFoot"><i class="icon-footprint-right-d"></i></button>
            </div>

            <div class="hideFirst" id="hydrogen">
                <h2>Good for you, you produce no negative Co2 emission with your vehicle!</h2>
                <button type="button" id="carsnow" class="carBtn btnFoot"><i class="icon-footprint-right-d"></i></button>
            </div>

            <div class="hideFirst" id="transportation">
                <h2>Why won't I display?</h2>
                <button type="button" data-next="" class="my-btn btnFoot"><i class="icon-footprint-right-d"></i></button>
            </div>
        </form>
        <div>
            <button id="backButton">Back</button>
        </div>
    </div>

希望能在这里找到一些帮助

好的,所以花了几天时间,但我想通了。

主要问题是 jquery.data- 属性仅在第一次访问 属性 时被读取。因此,当我在正确的时间更改它们时,它们并没有被阅读。这也是原因,虽然后退按钮有效,但它不允许您在返回问题时转到不同的 div。

这是 jQuery 文档中的一行:

"The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)."

Link to the page

通过根据必要的功能将 .data- 更改为 .attr 和 .prop 的组合,我能够使其正常工作。

正如我在最初的问题中提到的,我是新手,所以如果我没有提供足够的信息,请告诉我。

这是它正常工作的代码和 link to a fiddle

  var carCount = 0;

  $(document).ready(function () {

      // hide all 'hideFirst' elements, except the first one:
      $('.hideFirst:not(:first)').hide();

      var visited = [];

      // Method used to show/hide elements :
      function showNext(el) {
          // check if element has a 'nextitem' attribute:
          if (el.attr('nextitem')) {
              // hide all elements with 'hideFirst' class:
              $('.hideFirst').hide();
              // show 'Back' button:
              $('#backButton').show();
              // show the element which id has been stored in 'nextitem' attribute:
              $(el.attr('nextitem')).show();
              // Push the parent element ('.hideFirst') into visited array:
              visited.push(el.closest('.hideFirst'));
          }
      }
          // click event for 'back' button:
    $('#backButton').click(function () {
        // hide all elements with 'hideFirst' class:
        $('.hideFirst').hide();
        // remove the last '.hideFirst' element from 'visited' array and show() it:
        visited.pop().show();
        // hide 'back' button if visited array is empty:
        visited.length || $(this).hide();
    }).hide(); // hide 'back' button on init

      $(".myBtn").click(function () {
          showNext($(this));
      });

      $("#amount").click(function () {
          numberOfCars = parseInt(document.getElementById("inputNumber").value);
          showNext($(this));
      });


      $("#typeA").change(function () {

          carChoice = $("#typeA").val();
          $("#typeA").attr("nextitem", "#" + carChoice);
          showNext($(this));
        //clears previous choices
          $('#typeA').prop('selectedIndex', 0);
          $('#typeB').prop('selectedIndex', 0);
          $('#typeC').prop('selectedIndex', 0);
      });

      //Decides how many more times to iterate through
      $(".carBtn").click(function () {
          carCount++;
          //asks about other cars
          if (carCount < numberOfCars) {
              $(this).attr('nextitem', '#main');
              $("#bar").html(carCount);
              $("#foo").html(numberOfCars);
          }
          //moves on to the next category
          else {
              $(this).attr('nextitem', '#last');
              $("#bar").html(carCount);
          }
          showNext($(this));
      });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <form>
        <div class="hideFirst">
            <label for="inputNumber">Number of times to iterate through</label>
            <input type="text" id="inputNumber" />
            <button type="button" nextitem="#main" class="myBtn" id="amount">Next</button>
        </div>
        <div class="hideFirst" id="main">
            <select id="typeA">
                <option disabled selected>--Choose One--</option>
                <option value="b">Option B</option>
                <option value="c">Option C</option>
            </select>
        </div>
        <div class="hideFirst" id="b">
            <label for="typeB">Type B</label>
            <select id="typeB">
                <option disabled selected>--Choose One--</option>
                <option value="a">Option a</option>
                <option value="b">Option b</option>
                <option value="c">Option c</option>
            </select>
            <button type="button" class="carBtn">Next</button>
        </div>
        <div class="hideFirst" id="c">
            <label for="typeC">Type C</label>
            <select id="typeC">
                <option disabled selected></option>
                <option value="a">Option a</option>
                <option value="b">Option b</option>
                <option value="c">Option c</option>
            </select>
            <button type="button" class="carBtn">Next</button>
        </div>
        <div class="hideFirst" id="last">
            <p>Done</p>
        </div>
    </form>
    <div>
        <br/>
        <button id="backButton">Back</button>
    </div>
    <div>
        <p>Number of times you asked for:<span id="foo"></span>
        </p>
        <p>Number of times around this form:<span id="bar"></span>
        </p>
    </div>