javascript - Change class jquery -


good evening, can not run code: in practice, add new class not delete old one. it's simple system of , dislike

$query2 = mysql_query("select * totlike id_user_like = $id_user , id_post_like = ". $risultato['id']."");  if (mysql_num_rows($query2) == 1) {   $like = '<i class="glyphicon glyphicon-heart" id="'. $risultato['id'] .'"></i>'; } else {   $like = '<i class="glyphicon glyphicon-heart-empty" id="'. $risultato['id'] .'"></i>'; } 
var elem = $('#' + id_post).attr('class'); if (elem == "glyphicon glyphicon-heart") {   $('#' + id_post).removeclass('glyphicon glyphicon-heart').addclass('glyphicon glyphicon-heart-empty');   } else {     $('#' + id_post).removeclass('glyphicon glyphicon-heart-empty').addclass('glyphicon glyphicon-heart'); } 

i have cleaned code little, seems fine. not sure if snippet below shows working fine.

function toggleheart(id_post) {      var element = $('#' + id_post);      if (element.hasclass("glyphicon-heart")) {          element.removeclass('glyphicon-heart');          element.addclass('glyphicon-heart-empty');        } else {          element.removeclass('glyphicon-heart-empty');          element.addclass('glyphicon-heart');      }  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">    <p>click on button or heart toggle</p>  <i class="glyphicon glyphicon-heart" id="1" onclick="toggleheart(1)">1</i>  <button onclick="toggleheart(1)">toggle</button>  <br />  <i class="glyphicon glyphicon-heart-empty" id="2" onclick="toggleheart(2)">2</i>  <button onclick="toggleheart(2)">toggle</button>


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -