如何在jquery中获取节点元素的索引

时间:2017-10-18 21:21:16

标签: javascript jquery html css reactjs

我正在尝试获取p标记的索引,以便当用户点击它时,p标记将更改颜色或文本大小(可能两者都有)。我正在使用reactjs,但我正在尝试在jquery中执行它。我给每个p标签一个数据和名称属性。这是我的代码。如何使它只有被点击的元素获得css更改,以便用户知道它被选中。运行p标签的函数位于HTML showChapters函数中。

curl localhost:5601/api/kibana/settings/defaultIndex\
    -H "Content-Type: application/json"\
    -H "Accept: application/json, text/plain, */*"\
    -H "kbn-xsrf: alert"\
    -H "Connection: keep-alive"\
    --data-binary "{\"value\":\"alert\"}" -w "\n"
$(onReady)


function onReady() {

    $("#voteSearchInput").submit(function (e) {
        e.preventDefault();
        return false;
    });//end of voteSearchInput

    $('#root').on('click', '.bookChapters' ,() => {
        console.log('clicked')

        //I want to change the color here 
        
        
    });

}//end of onReady

1 个答案:

答案 0 :(得分:0)

React内置了可以利用的事件处理系统。有关详细信息see the docs.

在此,我将onClick分配给p元素并使用您定义的data-index

class Book extends React.Component {

  handleChapterClicked = (event) => {
    // you can get the index like this
    let pIndex = event.target.getAttribute("data-index");
    // your logic for the handler here
  }

  showChapters() {
    let chapterCount = this.state.chapterCount;
    let chapters = this.state.book.length;
    let chatpersArr = this.state.chapters;


    for(let i = 0; i < chapters; i++) {
        chatpersArr.push([])
    }


    return (
        chatpersArr.map((ch, id) => {
            chapterCount++;
            return (
                <p key={id} className='bookChapters' onClick={this.handleChapterClicked} data-index={id}>{this.state.book.book} Chapter:{chapterCount}</p>
            )
        })
    )
  }//end start
}

您可以删除data-index属性并将索引绑定为传递给handleChapterClicked的第一个参数:

<p key={id} className='bookChapters' onClick={this.handleChapterClicked.bind(this, id)} data-index={id}>{this.state.book.book} Chapter:{chapterCount}</p>

然后函数的定义将更改为:

handleChapterClicked = (index, event) => {
    // your logic for the handler here
}