I'm trying to clean up this function to target individual #hdid. I'm also using $this, but with no success.
<script>
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
// var id = $this.(".delete").val();
// var string = id ;
// console.log(id);
$.ajax({
type: "POST",
url: "delete-class.php",
data: {hdid: $('#hdid').val()},
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
//console.log(string);
}
});
return false;
});
});
</script>
2 Answers 2
If you refactor your code a bit you can do it this way. I'm also making the assumption that you mean .hdid instead of #hdid there should only be one hdid per page if it's really an ID and not a CLASS. Here's a quick sample if you're interested in seeing it in action.
<script>
var DeleteClass = function(hdid){
$.ajax{
type: "POST",
url: "delete-class.php",
data: {hdid: hdid.val()},
cache:false,
success:function(){
hdid.parent().slideUp('slow',function(){$(this).remove();});
}
}
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
$(this).children(".hdid").each(function(){
DeleteClass($(this));
});
$('#load').fadeOut();
return false;
});
});
</script>
-
\$\begingroup\$ Any reason you're using
DeleteClassinstead ofdeleteClass? By convention, only Constructor functions should start with an uppercase letter. \$\endgroup\$Joseph Silber– Joseph Silber2012年08月21日 18:42:07 +00:00Commented Aug 21, 2012 at 18:42 -
\$\begingroup\$ Also, please cache you selectors! \$\endgroup\$Joseph Silber– Joseph Silber2012年08月21日 18:42:44 +00:00Commented Aug 21, 2012 at 18:42
-
\$\begingroup\$ no reason, I don't really write a lot of javascript, so I don't know all the conventions. And I realize there's several things I could do to make it a little better. But the gist of it was the each function on hdid. \$\endgroup\$Matt Phillips– Matt Phillips2012年08月21日 23:02:25 +00:00Commented Aug 21, 2012 at 23:02
I think you actually want to do $(this) instead of $this. $this is a reserved word in PHP, not in JS/Jquery, so in your case it's undefined
$(this) on the other hand is the JQuery object of which your callback is a method of (in your case the clicked .delete element)
Just type $(this).val() and you will get the value of the clicked element.
-
\$\begingroup\$ that doesn't answer his question... \$\endgroup\$Matt Phillips– Matt Phillips2012年08月21日 13:01:10 +00:00Commented Aug 21, 2012 at 13:01