简体   繁体   English

如何在 textarea(HTML 标记)中写入 JavaScript object 以使用 documentQuerySelector 获取 object

[英]how to write JavaScript object in the textarea(HTML Tag) to get that object by using documentQuerySelector

I wanna write javascript object in Textarea or input field and wanna retrieve those data by using documentQuerySelector.我想在 Textarea 或输入字段中编写 javascript object 并想使用 documentQuerySelector 检索这些数据。 but when I do this it returns a string.但是当我这样做时,它会返回一个字符串。

IS there any way to write javascript code in the browser and access that code form my javascript file like app.js有没有办法在浏览器中编写 javascript 代码并从我的 javascript 文件(如 app.js)中访问该代码

HTML HTML

<textarea />

I use Event for the value In react我使用 Event 作为值 In react

JS / REACT I JS /反应

e.target.value

the object that i write in the text area我在文本区域中写的 object

{
  quizTitle: "React Quiz Component Demo",
  quizSynopsis: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim",
  questions: [
    {
      question: "How can you access the state of a component from inside of a member function?",
      questionType: "text",
      questionPic: "https://dummyimage.com/600x400/000/fff&text=X", // if you need to display Picture in Question
      answerSelectionType: "single",
      answers: [
        "this.getState()",
        "this.prototype.stateValue",
        "this.state",
        "this.values"
      ],
     correctAnswe": "3",
      messageForCorrectAnswer: "Correct answer. Good job.",
      messageForIncorrectAnswer: "Incorrect answer. Please try again.",
      explanation: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
     point: "20"
    }
  ]
} 

but when i retrieve the data and console.log it gives string instead of js object但是当我检索数据和console.log时,它给出了字符串而不是js object


"{
  quizTitle: "React Quiz Component Demo",
  quizSynopsis: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim",
  questions: [
    {
      question: "How can you access the state of a component from inside of a member function?",
      questionType: "text",
      questionPic: "https://dummyimage.com/600x400/000/fff&text=X", // if you need to display Picture in Question
      answerSelectionType: "single",
      answers: [
        "this.getState()",
        "this.prototype.stateValue",
        "this.state",
        "this.values"
      ],
     correctAnswe": "3",
      messageForCorrectAnswer: "Correct answer. Good job.",
      messageForIncorrectAnswer: "Incorrect answer. Please try again.",
      explanation: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
     point: "20"
    }
  ]
}"

The event.target.value for textarea in this case will return you a string在这种情况下,textarea 的event.target.value将返回一个字符串

If you want the object, you must use JSON.parse(textValue) to get it如果要 object,必须使用JSON.parse(textValue)来获取

Moreover, the textValue passed to JSON.parse must be a valid JSON (you could look at the MDN doc for more detail on what a valid JSON would look like)此外,传递给textValueJSON.parse必须是有效的 JSON (您可以查看MDN 文档以了解有关有效 JSON 的更多详细信息)

For example, to get it, you could declare an object and use JSON.stringify(obj) to get the valid JSON.例如,要获取它,您可以声明一个 object 并使用JSON.stringify(obj)来获取有效的 JSON。

 const a = { quizTitle: "React Quiz Component Demo", quizSynopsis: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim", questions: [ { question: "How can you access the state of a component from inside of a member function?", questionType: "text", questionPic: "https://dummyimage.com/600x400/000/fff&text=X", // if you need to display Picture in Question answerSelectionType: "single", answers: [ "this.getState()", "this.prototype.stateValue", "this.state", "this.values", ], correctAnswer: "3", messageForCorrectAnswer: "Correct answer. Good job.", messageForIncorrectAnswer: "Incorrect answer. Please try again.", explanation: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", point: "20", }, ], }; console.log(JSON.stringify(a, null, 2));

{
  "quizTitle": "React Quiz Component Demo",
  "quizSynopsis": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim",
  "questions": [
    {
      "question": "How can you access the state of a component from inside of a member function?",
      "questionType": "text",
      "questionPic": "https://dummyimage.com/600x400/000/fff&text=X",
      "answerSelectionType": "single",
      "answers": [
        "this.getState()",
        "this.prototype.stateValue",
        "this.state",
        "this.values"
      ],
      "correctAnswer": "3",
      "messageForCorrectAnswer": "Correct answer. Good job.",
      "messageForIncorrectAnswer": "Incorrect answer. Please try again.",
      "explanation": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
      "point": "20"
    }
  ]
}

After having a valid JSON string, paste it in the textarea, and when you get the value from textarea, just JSON.parse() that value to get your object value获得有效的 JSON 字符串后,将其粘贴到 textarea 中,当您从 textarea 获取值时,只需JSON.parse()该值即可获取您的 ZA8CFDE6331BD59EB2AC96F8911C4B6666

export default function App() {
  const [value, setValue] = React.useState('')

  const handleClick = () => {
    try {
      console.log(JSON.parse(value))
      alert('check the console log')
    } catch(err) {
      console.error(err)
      alert('not a valid JSON')
    }
  }
  
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <textarea rows="30" cols="60" value={value} onChange={e => setValue(e.target.value)}/>
      <br/>
      <button onClick={handleClick}>Get JSON</button>
    </div>
  );
}

编辑胡思乱想的形状 7hggw

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM