如何使用查询选择器单击

时间:2019-03-28 04:34:57

标签: javascript vue.js

我有一个导航项目列表,在加载时单击列表中的第一个元素

<li class="nav-item"  v-for="(checkoutplan, index) in checkoutplans" :key="checkoutplan.id">
     <a  class="nav-link" :class="{ 'active show' : index === 0 }" href="#settings" data-toggle="tab" @click="editModal(checkoutplan)">Checkout Plan {{index +1}}</a>
</li>

我在想什么

 document.querySelector("li[class='nav-item']").click()

document.querySelector("li.nav-item:first-child").click()

它不起作用

  created() {
        axios.get("api/checkoutplan")
        .then(({ data }) => {this.checkoutplans = data;document.querySelector("a.nav-link:first-child").click();});
    }

5 个答案:

答案 0 :(得分:1)

首先以

refs添加到HTML(在a标签处)。
<li class="nav-item"  v-for="(checkoutplan, index) in checkoutplans" :key="checkoutplan.id">
     <a  :id="'nav' + index" :ref="'nav' + index" class="nav-link" :class="{ 'active show' : index === 0 }" href="#settings" data-toggle="tab" @click="editModal(checkoutplan)">Checkout Plan {{index +1}}</a>
</li>

现在使用vuejs

$(this.$refs.nav0).click(function(){
    //nav0 is beacuse you want first element & first element index is 0
});

答案 1 :(得分:0)

作为您的评论,我尝试按以下方式在已挂载方法(未创建)中进行操作。当vue元素被数据修改时,请注意nextTick

new Vue({
 el: "#app",
 data: {
  checkoutplans : []
 },
 methods: {
   editModal : function(param) {
     console.log(param);
   }
 },
 mounted: function() {
   this.checkoutplans = [{id:1},{id:2}];
   this.$nextTick(() => {
   this.$el.querySelector("li.nav-item:first-child a").click();
   });
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li class="nav-item"  v-for="(checkoutplan, index) in checkoutplans" :key="checkoutplan.id">
     <a  class="nav-link" :class="{ 'active show' : index === 0 }" href="#settings" data-toggle="tab" @click="editModal(checkoutplan)">Checkout Plan {{index +1}}</a>
</li>
</ul>
</div>

您的代码似乎在api调用后先单击li!因此,您将调用的方法是editModal({firstItem})。直接调用方法而不用单击

axios.get("api/checkoutplan")
    .then(({ data }) => {this.checkoutplans = data;this.editModal(this.checkoutplans[0]) // direct call });
  

文档元素的创建方法尚未就绪,因此您无法在该方法中调用文档元素

答案 2 :(得分:-1)

var button = document.querySelector("input[type=button]");
button.addEventListener("click", function() {
  alert("button was clicked");
})

答案 3 :(得分:-1)

您将点击事件绑定在href a.nav-link标记中。不可以尝试

document.querySelector("a.nav-link:first-child").click()

答案 4 :(得分:-1)

document.querySelector('.nav-link');

请尝试以下代码。