如何将字符串转换为内部代码?

时间:2018-04-19 18:04:35

标签: javascript jquery

当我试图弄清楚jQuery是如何工作的时候。如何声明一个字符串然后将其转换为可由机器读取。简而言之,如何在不带引号的情况下放置字符串,以便字符串解析为document.querySelector,然后使用选择器添加括号。之前,我有eval(S)(.wrapper).className = "red";

我基本上想要实现评论的内容,这里是相关的代码:



const S = "document.querySelector";
S(".wrapper").className = "red"; 

/* Below is how I want the final result as. */
/* document.querySelector(".wrapper").className = "red" */

html, body {
    max-width: 100%;
    overflow-x: hidden;
    margin: 0;
    padding: 0;
}

.wrapper{
    width: 100%;
    height: 100vh;
    text-align: center;
    top: 50;
    left: 50;
    color: dodgerblue;
}

.red {
    color: red;
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Dom.js</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="wrapper">
        <h1>Dom.js</h1>
        <p>Making Dom Manipulation Easier!</p>
    </div>
    <script src="app.js"></script>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以创建一个返回document.querySelector(selector)

的函数

&#13;
&#13;
const S = (selector) => {
  return document.querySelector(selector)
}

// or 
/*
const S = function(selector) {
  return document.querySelector(selector)
}
*/

S(".wrapper").className = "red";
&#13;
html,
body {
  max-width: 100%;
  overflow-x: hidden;
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 100%;
  height: 100vh;
  text-align: center;
  top: 50;
  left: 50;
  color: dodgerblue;
}

.red {
  color: red;
}
&#13;
<div class="wrapper">
  <h1>Dom.js</h1>
  <p>Making Dom Manipulation Easier!</p>
</div>
&#13;
&#13;
&#13;

或按照建议in this post,不使用函数并保留上下文,请使用bind

&#13;
&#13;
var S = document.querySelector.bind(document)

S(".wrapper").className = "red";
&#13;
html,
body {
  max-width: 100%;
  overflow-x: hidden;
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 100%;
  height: 100vh;
  text-align: center;
  top: 50;
  left: 50;
  color: dodgerblue;
}

.red {
  color: red;
}
&#13;
<div class="wrapper">
  <h1>Dom.js</h1>
  <p>Making Dom Manipulation Easier!</p>
</div>
&#13;
&#13;
&#13;