如何随机获取属性

时间:2019-03-28 07:07:53

标签: javascript html attributes

我知道如何获取第一个def csv_to_json(): in_file = '/Elastic Search/Converted Detection/Converted CSV' out_file = '/Elastic Search/Converted Detection/Converted JSON' for filename in os.listdir(in_file): print("\n") print("Converting " + filename + " file...") with open(in_file + "/" + filename, 'r') as f: if filename.endswith(".csv"): reader = csv.DictReader(f, fieldnames=("location", "door_status", "date")) out = json.dumps([row for row in reader]) text_file = open(out_file + r'/{}.json'.format(filename[:-4]), 'w') text_file.write(out + "\n") 元素的type属性:

input
document.getElementById('button').addEventListener('click', function() {
  var type = document.querySelectorAll('input')[0].type;
  document.getElementById("p").textContent = type;
});

是否有一种方法可以随机获取<input type="text"> <input type="number"> <input type="url"> <button id="button">Get it</button> <p id="p"></p>属性,所以不必指定type索引吗?

2 个答案:

答案 0 :(得分:3)

您可以使用Math.random()获取输入length范围内的随机索引

document.getElementById('button').addEventListener('click', function() {
  var inputs = [...document.querySelectorAll('input')];
  let type = inputs[Math.floor(Math.random() * inputs.length)].type
  document.getElementById("p").textContent = type;
});
<input type="text">
<input type="number">
<input type="url">
<button id="button">Get it</button>
<p id="p"></p>

答案 1 :(得分:1)

  

是否有一种方法可以随机获取类型属性,所以不必指定输入索引?

如果哪一个都不重要,为什么不指定索引就获取第一个> python3 test.py 0.6363098297969493 0.7853979452340107 -6.274868388453119 1.0000000003382359 > 元素:

input
document.querySelector('button').addEventListener('click', function() {
  var type = document.querySelector('input').type;
  console.log(type);
});
input {
  width: 5em;
}