【问题标题】:Change action value using set attribute (DOM)使用设置属性 (DOM) 更改操作值
【发布时间】:2021-06-01 16:40:15
【问题描述】:

我有一个 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//');

【问题讨论】:

标签: javascript html jquery dom


【解决方案1】:

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//');

应该可以!

【讨论】:

  • 很抱歉,我的代码之前已经有该参数。我打错了。我也为 frmchld 做了一个错字。我已经更新了整个代码。谢谢..
  • 这对您有帮助吗?如果是,请点赞并标记为已回答!
  • 嘿,我的代码中已经有了它。但是当我在这里写它时,我犯了那个错误。即使使用此代码,它也不起作用。谢谢
  • 嗯,你有答案了吗?
【解决方案2】:

我终于找到了解决方案。我为表格设置了一个 ID,它开始工作了

const chld1 = BOX_1[0].querySelector('#form1'); chld1.setAttribute('action','http://')

const chld2 = BOX_1[0].querySelector('#form2'); chld2.setAttribute('action','http://')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2018-10-28
    相关资源
    最近更新 更多