触发具有$this的Jquery函数.onload和onclick



触发具有$this的Jquery函数。窗口加载和点击

function get_div_id(){
var f_id = $(this).attr("id");
alert(f_id);
}
$(window).load(function(){ 
get_div_id();
});
$('.divs_same_class_diferent_id').click(function() {
get_div_id();
});

正如你所推断的,这是行不通的,但你知道我想做什么,对吧?

根据代码的位置,它可能在创建DOM之前运行,在这种情况下,您试图将事件侦听器绑定到尚不存在的元素。试试这个:

function get_div_id(){
  var f_id = $(this).attr("id");
  alert(f_id);
}
$(document).ready(function(){
  $('.divs_same_class_diferent_id').click(get_div_id);
  // notice no anonymous function, this works because
  // we're passing in the function object for get_div_id
});

最新更新