使用此单击将一个变量附加到多个变量

时间:2016-04-16 11:15:53

标签: jquery

嗨,我有一个类似的工作代码

 $(document).on ("click", ".submit", function () {
    the_id = $(this).attr('data') ;
       });

 $(document).on ("mouseover", ".edit", function () {
    the_id = $(this).attr('data') ;
       });

  $(document).on ("mouseout", ".avoid", function () {
    the_id = $(this).attr('data') ;
       });

但它看起来非常响应这个变量the_id,因为每次我进行一些点击或鼠标悬停时我都必须定义它,我有许多onclick onmouseover具有相同的变量。

问题在于我无法将其作为全局变量,因为它具有$(this),它获取所单击元素的ID。

我怎么能这样做:

 the_id = $(this).attr('data') ; // how to define it here with $this() <------- 
 $(document).on ("click", ".submit", function () {
   // its defined here the_id ;
       });

 $(document).on ("mouseover", ".edit", function () {
   //its defined here the_id  ;
       });

  $(document).on ("mouseout", ".avoid", function () {
    // its defined here the_id  ;
       });

谢谢!

修改

Ibrahim说我创建了一个函数

但我得到的错误是id不是函数

   function id(){
        classList = $(this).attr("class").split(/\s+/);
        $.each(classList, function(index, item) {
       if (item.indexOf("user") > -1) {this_id = item;}
       if (item.indexOf("chatid") > -1) {this_chat_id = item;}
       });
     this_id = this_id.replace('user', '');
     this_chat_id = this_chat_id.replace('chatid', '');
  return [this_id, this_chat_id];
    }

2 个答案:

答案 0 :(得分:0)

您可以将这3行合并为一行,方法是指定用逗号分隔的所有元素,如下所示:

add3

或者你可以保留3行,但调用相同的功能:

$(document).on ("click mouseover mouseout", ".submit, .edit, .avoid", function () {
   the_id = $(this).attr('data') ;
});

答案 1 :(得分:0)

只需定义脚本标记的变量顶部打开,脚本中的所有函数都可以使用此变量。如下所示

<script>
   var the_id = '';

   __YOUR CODE__
</script>
相关问题