从单击事件的所有类中获取文本

时间:2015-03-21 04:54:57

标签: javascript jquery

有多个元素,每个元素都有类p1,p2,p3....p14所以,当我尝试从被点击的类中获取文本时,我会从所有类中获取文本!例如,当文字必须为80时,它将为808080080808080808080。有没有解决方法,除了给每个人ID

$('.p1,.p2,.p3,.p4,.p5,.p6,.p7,.p8,.p9,.p10,.p11,.p12,.p13,.p14').click(function(event) {
    if(!playerSelected) {
        playerName = this.title;
        // GETS TEXT FROM ALL CLASSES
        playerNumber = $('.' + this.className + '>strong').text();
        console.log(playerName + " : " + playerNumber);
        playerSelected = true;                   
    }
});

3 个答案:

答案 0 :(得分:3)

您需要单独查看该目标元素:

 playerNumber = $(this).find("strong").text();

现在它将仅从该目标元素中获取文本。

在你的情况下:

playerNumber = $('.' + this.className + '>strong').text();

您实际上是在查询具有匹配类名的所有元素。因此,它会从具有相同类名的所有元素返回文本。

答案 1 :(得分:1)

假设您的类元素中的强标记(如果不是仅使用

playerNumber = $(this).text();

试试这个

$('.p1,.p2,.p3,.p4,.p5,.p6,.p7,.p8,.p9,.p10,.p11,.p12,.p13,.p14').click(function(event) {
    if(!playerSelected) {
        playerName = $(this).title;
        // GETS TEXT FROM ALL CLASSES
        playerNumber = $(this).find("strong").text();
        // if strong tag are not in class element
        //playerNumber = $(this).text();
        console.log(playerName + " : " + playerNumber);
        playerSelected = true;                   
    }
});

此外,您可以为所有人分配一个呼叫,而不是使用p1,p2 ....

.pelement

像这样

$('.pelement').click(function(event) {
    if(!playerSelected) {
        playerName = $(this).title;
        // GETS TEXT FROM ALL CLASSES
        playerNumber = $(this).find("strong").text();
        // if strong tag are not in class element
        //playerNumber = $(this).text();
        console.log(playerName + " : " + playerNumber);
        playerSelected = true;                   
    }
});

答案 2 :(得分:0)

如果<strong>标记位于您的班级.p1,.p2 ...等内,那么您可以尝试这样做。

jQuery('.p1,.p2,.p3,.p4,.p5').click(function (event) {
    alert(jQuery(this).children('strong').text())
});

选中此fiddle

相关问题