如何获取我们点击的元素的索引

时间:2017-01-16 14:13:15

标签: javascript jquery meteor

我有一个容器列表,我想添加一个按钮,在我们点击终端徽标的容器上显示一个终端。 enter image description here

但我不知道如何捕捉列表中容器的索引。

我的HTML

<li class="liContainer">
    <div>
        <h3>{{nameContainer}}</h3>
    </div>
    <div id="idContainer">
        <span>ID: {{idContainer}}</span>
    </div>
    <div id="stateContainer">
        <span class="state">State: {{stateContainer}}</span>
    </div>

    <div id="terminalContainer" class="hidden">
      <div class="terminal hidden"></div>
    </div>

      <button type="button" class="stop {{#if to_hide_stop}}hidden{{/if}}"> </button>
      <button type="button" class="start {{#if to_hide_start}}hidden{{/if}}"> </button>
      <button type="button" class="pause {{#if to_hide_pause}}hidden{{/if}}"></button>
      <button type="button" class="unpause {{#if to_hide_unpause}}hidden{{/if}}"> </button>
      <button type="button" class="cmdLogs"> terminal </button>
</li>

我的JS:

'click .cmdLogs'(event) {
    Session.set("displayCmdLogs",true);
    //here I need to do something to get the ID with the event and then I could do...
    setTimeout(function(){
      var term = new Terminal();
      console.log("term:  " + term);
      //.. the getElement on the right one
      term.open(document.getElementsByClassName('terminal')[idFromEvent]);
      //term.fit();
      term.write('Hello from container.js');
    },200);
  }

1 个答案:

答案 0 :(得分:0)

我假设您想要捕获的ID是&#34; idContainer&#34;。我按如下方式修改您的HTML:

<li class="liContainer">
    <div>
        <h3>{{nameContainer}}</h3>
    </div>
    <div id="idContainer">
        <span>ID: {{idContainer}}</span>
    </div>
    <div id="stateContainer">
        <span class="state">State: {{stateContainer}}</span>
    </div>

    <div id="terminalContainer" class="hidden">
      <div class="terminal hidden"></div>
    </div>

      <button type="button" class="stop {{#if to_hide_stop}}hidden{{/if}}"> </button>
      <button type="button" class="start {{#if to_hide_start}}hidden{{/if}}"> </button>
      <button type="button" class="pause {{#if to_hide_pause}}hidden{{/if}}"></button>
      <button type="button" class="unpause {{#if to_hide_unpause}}hidden{{/if}}"> </button>
      <button type="button" class="cmdLogs" id="{{idContainer}}"> terminal </button>
</li>

你js:

'click .cmdLogs'(event, template) {
    Session.set("displayCmdLogs",true);
    var id = event.currentTarget.id; //The id is here

    setTimeout(function(){
      var term = new Terminal();
      console.log("term:  " + term);
      //.. the getElement on the right one
      term.open(document.getElementsByClassName('terminal')[idFromEvent]);
      //term.fit();
      term.write('Hello from container.js');
    },200);
  }