提问者:小点点

如何用HTML元素生成newArray?


我想做一个这样的数组:

let newArray = ["name", "email", "phone", "submit"]

从HTML中取出,如下所示:

 <div class="form-group">
      <label for="exampleInputEmail1">Name</label>
      </div>
      <div class="form-group">
        <label for="exampleInputEmail1">Email</label>
      </div>
    <div class="form-group">
      <label for="exampleInputPassword1">Phone</label>
    </div>
    <button type="button" class="btn btn-primary mb-2">Submit</button>

My code is this one: 

let textArray = []
let divText = "" 

$("div").each(function (){
    divText = $("div").text().replace (/(\r\n|\n|\r|[` `])/gi, ``)
    
})

textArray.push(divText)

但我得到的数组是这样的:

["NameEmailPhoneSubmitNameEmailPhone"]

共1个答案

匿名用户

这应该可以做到:

null

let textArray = []
let divText = $("div, button").map((i,x) => x.innerText.replace(/(\r\n|\n|\r|[` `])/gi, ``)).get();
console.log(divText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
  <label for="exampleInputEmail1">Name</label>
</div>
<div class="form-group">
  <label for="exampleInputEmail1">Email</label>
</div>
<div class="form-group">
  <label for="exampleInputPassword1">Phone</label>
</div>
<button type="button" class="btn btn-primary mb-2">Submit</button>

相关问题