如何获取javaScript事件源元素? [英] how to get javaScript event source element?

查看:103
本文介绍了如何获取javaScript事件源元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有一个像这样的按钮:


$ b有没有一种方法来检索内嵌的javaScript调用的元素源? $ b

 < button onclick =doSomething('param')id =id_button>动作< / button> 

注意:


  • 该按钮是从服务器生成的
  • 我无法修改生成过程

  • 在页面上生成了几个按钮,我只控制客户端。



我曾尝试过:

 函数doSomething(param){
var source = event.target || event.srcElement;
console.log(source);
}

在firebug上,我得到事件未定义



编辑:
在一些答案后,使用jQuery处理事件的重写是非常可接受的。我的问题是如何使用它的原始参数调用原始的onClick函数,而不知道函数名称。



代码:

 < button onclick =doSomething('param')id =id_button1> action1< / button> 
< button onclick =doAnotherSomething('param1','param2')id =id_button1> action2< / button> ;.
< button onclick =doDifferentThing()id =id_button3> action3< / button>


等等。

所以覆盖会是:

  $(document).on('click','button',function(e){
e.preventDefault();
$ / $ $ $(this).attr('onclick');
/ **
*在这里做什么来调用
* - doSomething(this,'param');如果按钮1被点击
* - doAnotherSomething(this,'param1','param2');如果button2被点击
* - doDifferentThing(this);如果button3被点击
*具有许多功能的按钮..
* /
});


解决方案

您应该将生成的HTML更改为不使用内嵌JavaScript ,并使用 addEventListener 代替。



如果不能以任何方式更改HTML,你可以得到 onclick 属性,使用的函数和参数,并将它转换为不显眼的javascript,而不是通过删除 onclick 处理程序和使用事件侦听器。



我们首先从属性获取值

  $('button')。each(function(i,el){var funcs = []; $(el).attr ('onclick')。split(';')。map(function(item){var fn = item.split('(')。shift(),params = item.match(/ \(([^) ] +)\)/),args; if(params& amp; params.length){args = params [1] .split(','); if(args&& args.length){args = args.map(function(par){return par.trim()。replace(/(')/ g,);});}} funcs (); $(el).data('args',funcs); //存储在jQuery的$ .data console.log($(el).data( 'args'));});  

< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< button onclick =doSomething('param')id =id_button1> action1< / button>< button onclick =doAnotherSomething('param1','param2')id =id_button1> action2< / button>。< button onclick =doDifferentThing id =id_button3> action3< / button>

这给了我们一个由 onclick 属性调用的所有和任何全局方法的数组,并且传递了参数,所以我们可以复制它。



然后,我们将删除所有内联javascript处理程序。

  $('button')。removeAttr('onclick')

并附加我们自己的处理程序

 <('button')。on('click',function(){...} 

在这些处理程序中,我们将获得存储的原始函数调用及其参数,并调用它们。

因为我们知道任何由inline javascript调用的函数都是全局函数,所以我们可以调用它们 window [functionName] .apply(this-value,argumentsArray),所以

 <$ c $ $('button')。on('click',function(){
var element = this;
$ .each(($(this).data('args')|| []),function(_,fn){
if(fn [0] in window)window [fn [ 0]]。apply(element,fn [1]);
});
});

在这个点击处理程序中,我们可以在调用原始函数之前或之后添加任何我们想要的东西。 / p>

一个工作示例

  $('button')。each(function(i,el){var funcs = []; $(el).attr('onclick')。split(';')。map函数(item){var fn = item.split('(')。shift(),params = item.match(/ \(([^)] +)\)/),args; if(params& amp (& args.length){args = args.map(function(par){return par.trim( ).replace(/(')/ g,);});}} funcs.push([fn,args || []]);}); $(el).data('args', funcs中) ('click',function(){console.log('click handler for'+ this.id);})。removeAttr('onclick')。 var element = this; $ .each(($(this).data('args')|| []),function(_,fn){if(fn [0] in window)window [fn [0]]。apply(element, fn [1]);}); console.log('after function call --------');});  

 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< ; button onclick =doSomething('param'); id =id_button1> action1< / button>< button onclick =doAnotherSomething('param1','param2')id =id_button2> action2< / button>。< button onclick =doDifferentThing )id =id_button3> action3< / button>< script>函数doSomething(arg){console.log('doSomething',arg)}函数doAnotherSomething(arg1,arg2){console.log('doAnotherSomething',arg1,arg2)}函数doDifferentThing(){console.log('doDifferentThing' ,'no arguments')}< / script>  

Is there a way to retrieve the element source of an inline javaScript call?

I have a button like this:

<button onclick="doSomething('param')" id="id_button">action</button>

Note:

  • the button is generated from server
  • I cannot modify the generation process
  • several buttons are generated on the page, I have control only on client side.

What I have tried:

function doSomething(param){
    var source = event.target || event.srcElement;
    console.log(source);
}

On firebug I get event is not defined

Edit: After some answers, an override of the event handling using jQuery is very acceptable. My issue is how to call the original onClick function with it's original prameters, and without knowing the function name.

code:

<button onclick="doSomething('param')" id="id_button1">action1</button>
<button onclick="doAnotherSomething('param1', 'param2')" id="id_button1">action2</button>.
<button onclick="doDifferentThing()" id="id_button3">action3</button>
.
.
and so on..

So the override would be:

$(document).on('click', 'button', function(e) {
  e.preventDefault();
  var action = $(this).attr('onclick');
  /**
   * What to do here to call
   * - doSomething(this, 'param'); if button1 is clicked
   * - doAnotherSomething(this, 'param1', 'param2'); if button2 is clicked
   * - doDifferentThing(this); if button3 is clicked
   * there are many buttons with many functions..
   */
});

解决方案

You should change the generated HTML to not use inline javascript, and use addEventListener instead.

If you can not in any way change the HTML, you could get the onclick attributes, the functions and arguments used, and "convert" it to unobtrusive javascript instead by removing the onclick handlers, and using event listeners.

We'd start by getting the values from the attributes

$('button').each(function(i, el) {
    var funcs = [];

	$(el).attr('onclick').split(';').map(function(item) {
    	var fn     = item.split('(').shift(),
        	params = item.match(/\(([^)]+)\)/), 
            args;
            
        if (params && params.length) {
        	args = params[1].split(',');
            if (args && args.length) {
                args = args.map(function(par) {
            		return par.trim().replace(/('")/g,"");
            	});
            }
        }
        funcs.push([fn, args||[]]);
    });
  
    $(el).data('args', funcs); // store in jQuery's $.data
  
    console.log( $(el).data('args') );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="doSomething('param')" id="id_button1">action1</button>
<button onclick="doAnotherSomething('param1', 'param2')" id="id_button1">action2</button>.
<button onclick="doDifferentThing()" id="id_button3">action3</button>

That gives us an array of all and any global methods called by the onclick attribute, and the arguments passed, so we can replicate it.

Then we'd just remove all the inline javascript handlers

$('button').removeAttr('onclick')

and attach our own handlers

$('button').on('click', function() {...}

Inside those handlers we'd get the stored original function calls and their arguments, and call them.
As we know any function called by inline javascript are global, we can call them with window[functionName].apply(this-value, argumentsArray), so

$('button').on('click', function() {
    var element = this;
    $.each(($(this).data('args') || []), function(_,fn) {
        if (fn[0] in window) window[fn[0]].apply(element, fn[1]);
    });
});

And inside that click handler we can add anything we want before or after the original functions are called.

A working example

$('button').each(function(i, el) {
    var funcs = [];

	$(el).attr('onclick').split(';').map(function(item) {
    	var fn     = item.split('(').shift(),
        	params = item.match(/\(([^)]+)\)/), 
            args;
            
        if (params && params.length) {
        	args = params[1].split(',');
            if (args && args.length) {
                args = args.map(function(par) {
            		return par.trim().replace(/('")/g,"");
            	});
            }
        }
        funcs.push([fn, args||[]]);
    });
    $(el).data('args', funcs);
}).removeAttr('onclick').on('click', function() {
	console.log('click handler for : ' + this.id);
  
	var element = this;
	$.each(($(this).data('args') || []), function(_,fn) {
    	if (fn[0] in window) window[fn[0]].apply(element, fn[1]);
    });
  
    console.log('after function call --------');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button onclick="doSomething('param');" id="id_button1">action1</button>
<button onclick="doAnotherSomething('param1', 'param2')" id="id_button2">action2</button>.
<button onclick="doDifferentThing()" id="id_button3">action3</button>

<script>
	function doSomething(arg) { console.log('doSomething', arg) }
    function doAnotherSomething(arg1, arg2) { console.log('doAnotherSomething', arg1, arg2) }
    function doDifferentThing() { console.log('doDifferentThing','no arguments') }
</script>

这篇关于如何获取javaScript事件源元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆