使用jQuery forEach查找原始单击发生的<p> </p>

时间:2011-10-11 13:58:03

标签: javascript jquery dom

我有<p>的列表,其中可能会产生一些点击。我理解如何用这样的东西滚动它们:

        $('p').each(function() { 

        });

但我不明白的是如何在这些段落中获取某些项目的值。我在这里查看API的属性:http://api.jquery.com/category/attributes/但不知怎的,我看到的相关内容不多。

以下是我<p>

的典型内容
<p class="half_text">0 
    <strong>
      <a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#" data-problem_id="48">Vote Up</a>
    </strong> 
    | 0 
    <strong>
        <a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#" data-problem_id="48">Vote Down</a>
    </strong>
</p>

我需要做的是增加或减少“half_text”内部或者在|之后的0整个事物中间的人物。我可以将它们包含在span标记内,但是如何将span标记与特定<p>的data-problem_id =“48”部分匹配?

谢谢!

6 个答案:

答案 0 :(得分:3)

我建议你将你的值包装成跨度以便更简单地阅读:

<p class="half_text">
    <span class="votes_up">
        0 
    </span>
    <strong>
      <a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#" data-problem_id="48">Vote Up</a>
    </strong> 
    |  
    <span class="votes_down">
        0 
    </span>
    <strong>
        <a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#" data-problem_id="48">Vote Down</a>
    </strong>
</p>

然后,脚本更简单,更容易阅读:

$('p.half_text a.vote_up').click(function(e){
    e.preventDefault();
    var votes = $(this).closest('span.votes_up');
    votes.text((+votes.text() || 0) + 1);
});
$('p.half_text a.vote_down').click(function(e){
    e.preventDefault();
    var votes = $(this).closest('span.votes_down');
    votes.text((+votes.text() || 0) + 1);
});

答案 1 :(得分:2)

您根本不需要使用每个循环。如果您在链接上处理点击,您可以执行以下操作:

var $this = $(this);
var p = $this.parentsUntil('p');
if($this.hasClass('vote_up')){
    $this.text(parseInt($this.text, 10) + 1);
}
else {
    $this.text(parseInt($this.text, 10) - 1);
}

答案 2 :(得分:1)

$('.vote_up').click(function(event) {
  var span = $(event.target).parent().find('.yourSpanClass');
  span.html(parseInt(span.html())+1);
};

我会留下你为vote_down做同样的事情。

答案 3 :(得分:1)

我认为这就是http://jsfiddle.net/7T4AK/

之后的情况

我添加了spans,因此您可以轻松访问需要增加的数字。 这应该让你走上正确的轨道,找出如何做同样的投票。

$('a.vote_up').click(function(){
    var span = $(this).closest('p').find('span.up');
    span.text(parseInt(span.text(),10) + 1);
});

答案 4 :(得分:0)

$('p').click(function(e){
    alert( $(e.target).html() );
});

从这里开始工作..

答案 5 :(得分:0)

您应该将数字包装在<span>标签中,然后您可以执行以下操作:

$('a', 'p.half_text').click(function(e) {
    var $this = $(this), $p = $this.closest('p.half_text'), $num, chg = 1;
    if($this.hasClass('vote_up')) {
        $num = $p.find('span.up');
    }
    else if($this.hasClass('vote_down')) {
        $num = $p.find('span.down');
        chg = -1;
    }
    $num.text(parseInt($num.text(), 10) + chg);
});

演示:http://jsfiddle.net/gRLad/7/