JQuery globalEval()方法
jQuery中的这个globalEval()方法是用来全局执行一些JavaScript代码。
语法:
jQuery.globalEval( code [, options ] )
参数: globalEval()方法接受上面提到的两个参数,并在下面加以说明。
- code。这个参数是要执行的JavaScript代码。
 - options = > nonce : 这个参数是传递给执行脚本的nonce属性。
 
返回值:它返回布尔值。
下面的例子说明了jQuery中globalEval()方法的使用。
例子1:在这个例子中,globalEval()方法在全局环境中执行一个脚本。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery | globalEval() method</title> 
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  
</head>
<body style="text-align:center;"> 
      
    <h1 style="color: green"> 
        GeeksForGeeks 
    </h1> 
      
    <h3>JQuery | globalEval() method</h3>
    <p>Execute a script in the global context.</p>
    <p id = "geeks"> </p>
    <script>
    function GFG() {
      jQuery.globalEval( "var newVar = 'Shubham Singh'" );
      document.getElementById("geeks").innerHTML = newVar;
    }
    GFG();
    </script>
</body>
</html>                                                                                                    
输出:

例子2:在这个例子中,globalEval()方法在一个启用了内容安全策略的网站上执行一个具有nonce值的脚本。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery | globalEval() method</title> 
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  
</head>
<body style="text-align:center;"> 
      
    <h1 style="color: green"> 
        GeeksForGeeks 
    </h1> 
      
    <h3>JQuery | globalEval() method</h3>
    <p>Execute a script with a nonce value on a<br>
    site with Content Security Policy enabled.</p>
    <p id = "geeks"> </p>
    <script>
    function GFG() {
      jQuery.globalEval( "var variable = true;", {
    nonce: "nonce-2726c7f26c"
  } );
      document.getElementById("geeks").innerHTML = variable;
    }
    GFG();
    </script>
</body>
</html>                                                                                                                                            
输出:

极客教程