【问题标题】:How to get the index of an node element in jqueryjquery如何获取节点元素的索引
【发布时间】:2018-03-30 21:00:18
【问题描述】:

我正在尝试获取 p 标签的索引,以便当用户单击它时,p 标签将改变颜色或文本大小(可能两者兼而有之)。我正在使用 reactjs,但我正在尝试在 jquery 中进行操作。我给每个 p 标签一个数据和名称属性。这是我的代码。我如何做到这一点,只有被点击的元素会发生 CSS 更改,以便用户知道它已被选中。运行 p 标签的函数在 HTML showChapters 函数中。

$(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
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {Link} from 'react-router-dom';
import Header from './Header.jsx';
import axios from 'axios';


class Book extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            book:Object,
            user:Object,
            chapters:[],
            chapterCount:0,
            ready:false,
        };//end of state

    }//end of constructor

    start() {
        console.log(this.state.book)
    }


    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' data-index={id}>{this.state.book.book} Chapter:{chapterCount}</p>
                )
            })
        )
    }//end start

    componentWillMount() {
        //Always gettting the last book out of the array
        

        //AUTHENTICATES THE USER
        axios.get('/login').then(res => {
            let userInfo = res.data;
            if(userInfo === "Not Authenticated") {
                window.location = "/?#/";
            } 
        });//end of axios GET

        //GETS THE CORRECT BOOK FROM THE REDUCER
        if(this.props.book.editBookReducer.length - 1 === -1) {
            window.location = "/?#/user";
        }
        else {
            let lastBook = this.props.book.editBookReducer.length -1;
            let book = this.props.book.editBookReducer[lastBook].data.book;
            let user = this.props.book.editBookReducer[lastBook].data.user;
            this.setState({book, user, ready:true});
        }
    }//end componentWillMount


    render() {

        if(!this.state.ready){
            return false;
        }
        else {
            return (
                <div>
                <Header/>
                <button onClick={this.start.bind(this)} >start</button>
                    <div className="container">
                        <div className="row" style={{"textAlign": "center"}}>
                            <div className="col-md-12">
                                <h1>{this.state.book.book}</h1>
                            </div>
                        </div>
                        <div className="row" style={{"textAlign": "center"}}>
                            <div className="col-md-6">
                                {this.showChapters()}
                            </div>
                            <div className="col-md-6">
                                <textarea name="" id="" cols="50" rows="60"></textarea>
                            </div>
                        </div>
                        
                    </div>
                </div>
            );
        }

        
    }
}//end class Book


function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        
    },
     dispatch)
}

function mapStateToProps(state) {
    return {
        book:state
    }
}




export default connect(mapStateToProps, mapDispatchToProps)(Book);

【问题讨论】:

  • "I am using reactjs, but I am trying to do it in jquery." 为什么会这样?使用 React.js 开发时不需要使用 jquery
  • 只用 reactjs 怎么做?
  • 我也建议在 React 中进行。但是如果你真的想在jQuery中做,不要在点击处理程序中使用箭头函数,那么this将是你点击的元素,所以理论上你可以定位它并直接改变它的属性。

标签: javascript jquery html css reactjs


【解决方案1】:

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
}

【讨论】:

    猜你喜欢
    • 2017-02-08
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 2012-04-10
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多