VG P
VG P

Reputation: 333

How to execute anonymous function using eval or Function

How to execute jquery using eval function

function hello(){
    console.log("hello");
}

$(function() {
    hello();
   
})(); 

I have above code as String value and passing to java script eval function. It's giving TypeError: $(...) is not a function. How to load Jquery dynamically and execute above code to print "hello" using eval/Function or $.globalEval.

Upvotes: 1

Views: 384

Answers (1)

Marik Ishtar
Marik Ishtar

Reputation: 3049

It works fine, you need to remove the last () from $(function() {}).

does this help ?

eval(`
  function hello(){
    console.log("hello");
  }

  $(function() {
    hello();
   
  });

`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions