GetElementById设置为null而不是int

时间:2014-02-09 03:28:28

标签: javascript php jquery html

我有一些代码只是获取一个id并将其分配给变量由于某种原因,当它应该是一个来自php for循环的整数时,notification_id被设置为null

的javascript

$(".pro_content_notification_remove").live('click', function (e) {

 var notification_id = document.getElementById(this);

 e.preventDefault(); 
 $(this).parent().remove();

});

的PHP / HTML

<?php 
    foreach($notification_array as $key => $value){



       echo '<div class="pro_content_notification_ele" id="'.$value.'">
                                    <div class="pro_content_notification_image '.$notification_image_id.'"></div><!--end pro_content_notifications_image-->
                                    <span class="pro_content_notification_text '.$viewed.'">'.$notification_text.'</span>
                                    <div class="pro_content_notification_remove"></div><!--end pro_content_notification_remove-->
                                </div><!--end pro_content_notification_ele-->';
                    }

    ?>

我已经检查了数组和页面源,并且在pro_content_notification_ele的id中设置的$ value肯定是1,所以为什么设置为null。

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

this引用事件处理程序中的dom元素,因此使用this.id来获取元素的ID。

$(".pro_content_notification_remove").live('click', function (e) {
    var notification_id = this.id;

    e.preventDefault(); 
    $(this).parent().remove();
});

注意:如果您使用的是jQuery&gt; = 1.7,请使用.on()代替.live()

答案 1 :(得分:1)

尝试使用,

var notification_id = e.target.id;

var notification_id = $(this).attr('id');

var notification_id = this.id;

代替,

var notification_id = document.getElementById(this);

答案 2 :(得分:1)

而不是使用

document.getElementById(this)

使用

$(this).attr('id')