【问题标题】:How can I click on the the first button, which is located in specific div with span class?? (using javascript)如何单击第一个按钮,该按钮位于具有跨度类的特定 div 中? (使用JavaScript)
【发布时间】:2021-03-05 00:36:18
【问题描述】:

我正在尝试导航 javascript 以单击第一个按钮,该按钮位于 div class="important" 中,并且 div 还必须包含 span class="something"。页面上还有其他 div,但并非所有 div 都包含 span 类。有没有办法在javascript中做到这一点?我尝试了几次,但没有任何效果。 我会很高兴得到任何建议。 谢谢

页面代码如下:

...
<div class="important">
     <div>
          <span class="something">...</span>
     </div>
     <input type="button" value="Test" name="bid" class="other class">                         
</div>

<div class="important">
...
</div>

【问题讨论】:

  • 你的问题非常模糊不清。 how can I click on the first button? 这是什么意思?您使用鼠标并将其悬停在按钮上,然后用手指单击鼠标左键... I am trying to navigate javascript to click on the first button 为什么 JS 应该单击按钮?为什么使用输入类型作为按钮?你到底想做什么?

标签: javascript html css


【解决方案1】:

如果我理解您的问题,您想在包含 .something 类的第一个 .important div 上找到一个按钮。有了你的标记,你可以这样做:

document.querySelectorAll('.important .something')[0].parentElement.parentElement.querySelector('[type="button"]');

现在如果你想点击它,你可以添加.click()

演示:

function demo(btn) {
  // jsut for demo
  alert(btn.value);
};
function findBtn() {
  document.querySelectorAll('.important .something')[0].parentElement.parentElement.querySelector('[type="button"]').click();
}
<button id="findmybtn" onclick="findBtn()">Find my button and click on it</button>
<div class="important">
    <div><span class="notsomething">notsomething</span></div>
    <input type="button" value="Test1" name="bid" class="other class" onclick="demo(this)">                         
</div>
<div class="important">
    <div><span class="something">something</span></div>
    <input type="button" value="Test2" name="bid" class="other class" onclick="demo(this)">                         
</div>
<div class="important">
    <div><span class="somethingelse">somethingelse</span></div>
    <input type="button" value="Test3" name="bid" class="other class" onclick="demo(this)">                         
</div>
<div class="important">    
    <input type="button" value="Test4" name="bid" class="other class" onclick="demo(this)">                         
</div>
<div class="important">
    <div><span class="something">something</span></div>
    <input type="button" value="Test5" name="bid" class="other class" onclick="demo(this)">                         
</div>

【讨论】:

  • (你节省了我的时间);)
  • 没有问题享受编码!
猜你喜欢
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 2017-03-09
  • 2022-07-29
  • 2019-09-21
相关资源
最近更新 更多