extractScripts
extractScripts() -> [script...]
提取出字符串中包含的所有 script
的内容,并将之返回作为一个字符串数组。
这个方法被用于 String#evalScripts 内部。它并 不会 执行脚本块中的代码 (如果要执行代码,请使用 String#evalScripts),但如果你要延后执行这些脚本块中的代码, 它会非常有用。
样例
'lorem... <script>2 + 2</script>'.extractScripts();
// -> ['2 + 2']
'<script>2 + 2</script><script>alert("hello world!")</script>'.extractScripts();
// -> ['2 + 2', 'alert("hello world!")']
注意
为延后执行脚本块中的代码,你可以使用下面的方法:
var myScripts = '<script>2 + 2</script><script>alert("hello world!")</script>'.extractScripts();
// -> ['2 + 2', 'alert("hello world!")']
var myReturnedValues = myScripts.map(function(script) {
return eval(script);
});
// -> [4, undefined](并且弹出对话框显示 'hello world!')