JQuery: function call dynamically

I bound the onClick event handler to the tag. When I clicked, I wanted to get an attribute - say, fn; and I want to call the function referred to as the attribute value.

The following code does not work

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
    <script language="JavaScript">
        var Test = Test? Test : new Object();
        $(document).ready(function(){
            Test.main();
        })
        Test.sub = function(){
            alert('called');
        }
        Test.main = function(){
            $('.caller').click(function(e){
                e.preventDefault();
                var fn = $(this).attr('fn');
                alert('calling: '+fn);
                return fn();
            });
        }
    </script>
</head>
<body>
    <a class="caller" fn="Test.sub" href="#">test call</a>
</body>
</html>

My questions

  • Is it possible?
  • What am I doing wrong?
  • What could be the right approach to solve this problem?

Thanks
Nishant

+3
source share
2 answers

Is it possible?

Yes. If you changed your link, simply sub:

<a class="caller" fn="sub" href="#">test call</a>

Then it works:

$('.caller').click(function(e){
    e.preventDefault();
    var fn = $(this).attr('fn');
    alert('calling: '+fn);
    return Test[fn]();
});

, , . , ([]), :

Test.sub();
Test['sub']();
var fn = 'sub';
Test[fn]();

?

. "Test.sub" , , , . :

"Test.sub"();

.... , .: -)

?

. , " ", Test , ...

: , eval. , , . eval .


# 1: fn ( = validate). HTML4 , , - , ( ). HTML5, , , data-, , . , ( ), data-fn="sub", fn="sub". .


# 2. , {}, new Object(). :.

var Test = Test? Test : {};

, - || :

var Test = Test || {};
+14

:

<a class="caller" fn="Test.sub()" href="#">test call</a>

$('.caller').click(function(e){
    e.preventDefault();
    var fn = eval($(this).attr('fn'));
    fn;
});
-1

Source: https://habr.com/ru/post/1781604/


All Articles