javascript - 在按钮之前查找 div

标签 javascript jquery

当单击按钮时,我尝试将Class添加到向导步骤,但仍然没有运气:/

 <div class="mt-4">
    <div class="wizard-steps">
      <div class="wizard-step">
        <div class="wizard-step-icon">
          <i class="far fa-user"></i>
       </div>
    </div>

    <form class="wizard-content mt-2" id="regForm">
    <fieldset>
    <div class="form-group row">
        <div class="col-lg-4 col-md-6 text-right">
            <button type="button" onclick="step0(this);" class="btn">Next</button>
        </div>
     </div>
    </fieldset>
    </form>
  </div>

JavaScript:

<script>
 function step0(element) {
  $(element).prev('div').find('.wizard-step').addClass('wizard-step-active');
      }
</script>

谁能帮帮我吗?

最佳答案

prev用于检索前一个同级元素。 .wizard-step您想要的目标是被单击按钮的父级的兄弟级的子级。因此,您需要使用 closest()相反。

另请注意 onclick (以及所有其他 onX 属性)不是好的做法,应该避免。由于您已经在使用 jQuery,因此您可以不显眼地附加事件,如下所示:

jQuery($ => {
  $('.btn').on('click', function() {
    $(this).closest('.wizard-steps').find('.wizard-step').addClass('wizard-step-active');
  });
});
.wizard-step-active { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mt-4">
  <div class="wizard-steps">
    <div class="wizard-step">
      <div class="wizard-step-icon">
        <i class="far fa-user">User icon</i>
      </div>
    </div>
    <form class="wizard-content mt-2" id="regForm">
      <fieldset>
        <div class="form-group row">
          <div class="col-lg-4 col-md-6 text-right">
            <button type="button" class="btn">Next</button>
          </div>
        </div>
      </fieldset>
    </form>
  </div>

或者,不要调用 find()从共享父级中,您可以选择 form并使用prev() :

$('.btn').on('click', function() {
  $(this).closest('.wizard-content').prev('.wizard-step').addClass('wizard-step-active');
});

两者都可以,这仅取决于您的 HTML 结构如何最适合此用例。

关于javascript - 在按钮之前查找 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60458678/

相关文章:

javascript - 如何比较两个字符串并获得不同的部分

javascript - switch 语句中的 bool 运算符?

未找到 Javascript 文件

javascript - 汉堡导航,如何隐藏/显示链接

jquery - 如何为本节添加类(class)

javascript - 从谷歌代码链接 jquery.cookie.js?

javascript - 在导航栏中显示未读计数

javascript - 浏览器有时会显示 JSON 文本而不是所需的页面

jquery - 重新定位 jQuery 警报

javascript - 在 Angular 数组上使用 splice() 时,jQuery 选择器跳转到下一项