简体   繁体   English

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

[英]Trigger a Jquery function that has $this. onload and onclick

Trigger a Jquery function that has $this. 触发具有$ this的Jquery函数。 on window load and on click 加载窗口并单击

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();
});

As you can deduce, this will not work, but you have an idea of what I'm trying to do, right? 可以推断,这是行不通的,但是您对我正在尝试执行的操作有所了解,对吗?

Depending on where that code is it may be running prior to the DOM being created in which case you're attempting to bind event listeners to elements that do not yet exist. 根据创建该代码的位置,代码可能会在创建DOM之前运行,在这种情况下,您尝试将事件侦听器绑定到尚不存在的元素。 try this: 尝试这个:

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM