首页 > 解决方案 > 使用设置属性 (DOM) 更改操作值

问题描述

我有一个 HTML 文件,其中包含一个名为 column 的类中的 2 个表单。

 <div class="column">

       <form  action="" method="post" >              
  
       <button type="submit" class="button">ON</button>
                                                    
       </form>
                               
        
      <form action =""  method="post" > 
                                    
      <button type="submit" class="button2">OFF</button>
                                   
      </form>

</div>
                               

我可以使用下面使用的方法更改 2 个表单中的标题等(未包含在此代码中)。但是,我不知道为什么我无法使用相同的原理更改“动作”值。

目标:我想知道如何选择表单内的操作并设置属性

我试过的

const BOX = document.querySelectorAll('.column');  //selects the entire class

const child1 = BOX[0].querySelectorAll('form');  //selects all forms

const formchild = child1[0].querySelector('p :nth-child(2)');  // selects form 1
formchild.setAttribute('action', 'http://xxxxxx//'); 

const formchild2 = child1[1].querySelector('p :nth-child(1)'); // selects form 2
formchild2.setAttribute('action', 'http://xxxxxx//');

标签: javascripthtmljquerydom

解决方案


element.querySelectorAll 返回一个数组:因此

const BOX = document.querySelectorAll('.column');  //selects the entire class
// changed it here 
const child1 = BOX[0].querySelectorAll('form');  //selects all forms

let formchild1 = child1[0].querySelector('p :nth-child(2)');  // selects form 1 
// WHAT IS THIS DOWN HERE, please give additional info
formchild1.setAttribute('action', 'http://xxxxxx//'); 

let formchild2 = child1[1].querySelector('p :nth-child(1)'); // selects form 2
formchild2.setAttribute('action', 'http://xxxxxx//');

应该管用!


推荐阅读