【问题标题】:Add .attr to button not working when called调用时将.attr 添加到按钮不起作用
【发布时间】:2015-03-22 19:17:06
【问题描述】:

不确定我的问题格式是否正确。手动添加了“data-next”,它在适当的时候发生了变化,但仍然没有变化。已将其缩小到“showNext”功能。

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

我的问题是,虽然它确实迭代了正确的次数,并且 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>

希望能在这里得到帮助

【问题讨论】:

  • 你可以用$("#carType").attr("data-next", "#"+carChoice);替换你的大量ifelse
  • 很公平。仍在学习可以缩短内容的地方。谢谢。

标签: javascript jquery html attr


【解决方案1】:

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

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

这是 jQuery 文档中的一行:

"data-属性在data属性第一次被拉取 被访问,然后不再被访问或变异(所有数据值 然后存储在 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>

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    相关资源
    最近更新 更多