针对同胞元素的孩子

时间:2018-08-22 04:55:59

标签: javascript html

以下代码将fieldsets作为兄弟姐妹,以便在上一个fieldsets中选择input buttons时才能启用它们。

document.querySelectorAll("fieldset").forEach(fieldset => {
  fieldset.addEventListener("change", function() {
    let nextFieldset = this.nextElementSibling

    while (nextFieldset && !nextFieldset.disabled) {
      nextFieldset = nextFieldset.nextElementSibling
    }

    if (nextFieldset) {
      nextFieldset.disabled = false
    }
  })
})

<form>
  <fieldset> … </fieldset>
  <fieldset> … </fieldset>
  <fieldset> … </fieldset>
</form>
  

如何定位位于单独的fieldsets中的sections

<form>
  <section><fieldset> … </fieldset></section>
  <section><fieldset> … </fieldset></section>
  <section><fieldset> … </fieldset></section>
</form>

2 个答案:

答案 0 :(得分:1)

这是完整的工作解决方案:

document.querySelectorAll("section").forEach(section => {
  section.addEventListener("change", function() {
    let nextFieldset = this.nextElementSibling.querySelector("fieldset")

    while (nextFieldset && !nextFieldset.disabled) {
      nextFieldset = nextFieldset.nextElementSibling
    }

    if (nextFieldset) {
      nextFieldset.disabled = false
    }
  })
})

答案 1 :(得分:0)

我认为这可以解决您的问题

    document.querySelectorAll("fieldset").forEach(fieldset => {
  fieldset.addEventListener("click", function() {
    let nextFieldParent = this.parentElement.nextElementSibling;
    let nextFieldset = nextFieldParent.firstElementChild;    
    while (nextFieldset && !nextFieldset.disabled) {
      nextFieldParent = this.parentElement.nextElementSibling;
    nextFieldset = nextFieldParent.firstElementChild;
    }

    if (nextFieldset) {
      nextFieldset.disabled = false
    }
  })
})