如何将html的属性获取到jquery

时间:2018-12-22 09:16:57

标签: php jquery html

我试图按照教程的指导实现“喜欢”和“不喜欢”按钮来评论,但是我无法从代码中获取属性。

这是我的html代码,包括php

<a id="' . $quote->quote_id . '" data-toggle="tooltip" title="'. $language->list->tooltip->like .'" class="clickable like tooltipz"><span class="glyphicon glyphicon-plus red"></span></a>&nbsp;

<span class="up_votes"><?php echo ($vote_up); ?></span>

<a id="' . $quote->quote_id . '" data-toggle="tooltip" title="'. $language->list->tooltip->dislike .'" class="clickable dislike tooltipz"><span class="glyphicon glyphicon-minus red"></span></a>&nbsp;

<span class="up_votes"><?php echo ($vote_down); ?></span>

$quote->quote_id is integers like 1,2
$language->list->tooltip->like = Like comment
$language->list->tooltip->dislike = Dislike comment
$vote_up = total likes
$vote_up = total dislikes

这是jquery部分

//####### on button click, get user like and send it to vote_process.php using jQuery $.post().
    $(".glyphicon").on('click', '.glyphicon', function (e) {

        //get class name (down_button / up_button) of clicked element
        var clicked_button = $(this).children().attr('class');

        //get unique ID from voted parent element
        var quote_id    = $(this).parent().attr("id"); 

        if(clicked_button==='glyphicon-minus') //user disliked the content
        {
            //prepare post content
            post_data = {'quote_id':quote_id, 'vote':'down'};

            //send our data to "vote_process.php" using jQuery $.post()
            $.post('processing/process_votes.php', post_data, function(data) {

                //replace vote down count text with new values
                $('#'+quote_id+' .down_votes').text(data);

                //thank user for the dislike

            }).fail(function(err) { 

            //alert user about the HTTP server error
            alert(err.statusText); 
            });
        }
        else if(clicked_button==='glyphicon-plus') //user liked the content
        {
            //prepare post content
            post_data = {'quote_id':quote_id, 'vote':'up'};

            //send our data to "vote_process.php" using jQuery $.post()
            $.post('processing/process_votes.php', post_data, function(data) {

                //replace vote up count text with new values
                $('#'+quote_id+' .up_votes').text(data);

                //thank user for liking the content
            }).fail(function(err) { 

            //alert user about the HTTP server error
            alert(err.statusText); 
            });
        }

    });
    //end 

        });

在jquery部分中,我试图知道用户单击了哪个按钮并获取该按钮的ID

2 个答案:

答案 0 :(得分:2)

  

.attr('class')将返回分配给该元素的所有类,当您将整个类列表与特定类(即'class1 class2 class2'!='class2')进行比较时,该类将不起作用。   


  .hasClass('specific-class')将返回一个布尔值,具体取决于是否已将特定类分配给了所讨论的元素。

推荐的解决方案

您可以稍微简化一下代码,在使用.glyphiconhasClass(".glyphicon-minus")之前,下面的代码将单击事件附加到类hasClass(".glyphicon-plus")的任何对象上投票。

从这里有两种选择来更新每个帖子的总投票,您可以使用当前的技术(找到最近的包装类-在此示例中使用了.post),也可以添加属性标识属于该帖子的元素的UI元素-即for="post1"

我已经包含了第二个选项的代码,因为它有点短,但将其注释掉了。

还进行了一项检查,以查看新的总数是否为0,这将停止该过程,从而使您无法获得否定票。我已将此支票留为注释,但是如果需要,您可以取消注释。

希望有帮助,如果您还有其他需要,请告诉我。

$(".glyphicon").click(function() {

  vote = 0;

  // Check if negative vote
  if ($(this).hasClass("glyphicon-minus")) {
    vote = -1;
  }

  // Check if positive vote
  if ($(this).hasClass("glyphicon-plus")) {
    vote = 1;
  }


  // Update individual vote count
  newVoteTotal =  
  parseInt($(this).closest(".post").find(".votes").text()) + parseInt(vote);

  // Uncomment if statement and closing bracket if you want to stop usings from being able to give negative votes
  //if ( newVoteTotal != "-1" ) {
  $(this).closest(".post").find(".votes").text( newVoteTotal );
  //}


  // ALTERNATIVE using 'for' attributes
  // postID = $(this).attr("for");
  // newVoteTotal = parseInt($(".votes[for='" + postID + "']").text()) + parseInt(vote);
  // $(".votes[for='" + postID + "']").text(newVoteTotal)

})
.post {
  padding: 20px;
  border: 1px solid black;
}

.post-body {
  padding-bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post" id="post1">
  <div class="post-body">
    Lorem ipsum post 1.
  </div>
  <button class="glyphicon glyphicon-plus" for="post1">Vote Up</button>
  <button class="glyphicon glyphicon-minus" for="post1">Vote Down</button>
  <span class="votes" for="post1">0</span>
</div>
<div class="post" id="post2">
  <div class="post-body">
    Lorem ipsum post 2.
  </div>
  <button class="glyphicon glyphicon-plus" for="post2">Vote Up</button>
  <button class="glyphicon glyphicon-minus" for="post2">Vote Down</button>
  <span class="votes" for="post2">0</span>
</div>


特定解决方案

我已经尝试为您的代码结构创建特定的解决方案,我相信这会起作用。更改包括:

  • $(".glyphicon").on('click', function(e) {-更正了点击事件的创建方式
  • var clicked_button = $(this).attr('class')-如果愿意,您可以收集所有课程(稍后我们将检查单个课程的存在情况).attr() docs
  • if (clicked_button.includes('glyphicon-minus')-这将检查我们早期收集的类的完整列表,以查看是否存在特定的类(如果存在,则返回true)。 .include() docs

我删除了发送信息服务器端的所有代码,并用console.log()消息替换了该代码,以证明我们已收集了所需的所有参数。您可以为生产站点重新添加旧代码。

//####### on button click, get user like and send it to vote_process.php using jQuery $.post().
$(".glyphicon").on('click', function(e) {

//get class name (down_button / up_button) of clicked element
var clicked_button = $(this).attr('class');

//get unique ID from voted parent element
var quote_id = $(this).parent().attr("id");

if (clicked_button.includes('glyphicon-minus')) //user disliked the content
{
  // POST like
  console.log("Liked quote-id=" + quote_id + " (via class " + clicked_button + ")");
 
} else if (clicked_button.includes('glyphicon-plus')) //user liked the content
{
  // POST dislike
  console.log("Disliked quote-id=" + quote_id + " (via class " + clicked_button + ")");
}

});
//end 
.glyphicon {
  width: 50px;
  height: 50px;
  display: inline-block;
}

.red {
  background: red;
}

.like {
  border-bottom: 5px solid green;
}

.dislike {
  border-bottom: 5px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a id="1" data-toggle="tooltip" title="Like comment" class="clickable like tooltipz"><span class="glyphicon glyphicon-plus red"></span></a>&nbsp;

<span class="up_votes">0</span>

<a id="1" data-toggle="tooltip" title="Dislike comment" class="clickable dislike tooltipz"><span class="glyphicon glyphicon-minus red"></span></a>&nbsp;

<span class="up_votes">0</span>

答案 1 :(得分:0)

第一:

$(".glyphicon").on('click', '.glyphicon', function (e) {
//you need to change it to 
$(document).on('click', '.glyphicon', function (e) { // if its dynamically generated element or you toggle `.glyphicon` class .. 
 // else you can just use
$('.glyphicon').on('click' , function(){
   //code here
})

2nd:要检查类,您需要使用hasClass

然后在下一行

var clicked_button = $(this).children().attr('class');

您已经处于glyphicon的点击事件中,因此无需在此处使用children()。如果您console.log($(this).attr('class')),它将输出glyphicon glyphicon-plus red

var clicked_button = $(this);
if(clicked_button.hasClass('glyphicon-minus')){

}

注意:在更改了上面带有我的通知的代码后,您可以console.log(quote_id)