我正在开发一个chrome扩展程序,该扩展程序会将HTML中的标识符提取到var中,并且该var将用于填写表单字段。
我尝试用Js完成此操作。但在控制台中收到以下错误:
“未捕获的TypeError:无法将属性'value'设置为null”
<input type="text" name="currId" placeholder="Current ID" id="searchInput">
someId = "some-thing-nice
<!--somehow, the line below was throwing the error with the /value. reddit,stack overflow, and random googling confirmed that I was calling an ID that did not exist in the html/ But it definetly did exist. -->
document.getElementById("searchInput").value = someId;
var webID = (document.getElementById("searchInput").value = someId;
console.log(someId);
我最终实现了jquery。
//this Id is polled from another piece of code and passed to the var someID
var someId = "some-thing-nice";
//sets the property with the id searchInput to the var above
$("#searchInput").val(someId);
//this code can be commented out. currSomeId was to be used to validate the copy
var currsomeId = $("#searchInput").val(someId);
window.alert($("#searchInput").val());
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="chrome-extension.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="chrome-extension.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Chrome Extension</title>
</head>
<body>
<div class="container">
<h1 class="application-heading">someID Extension</h1>
<hr>
<p class="program-desc">Some Text</p>
<!-- this field to be populated -->
<input type="text" name="currWebID" placeholder="Current someID" id="searchInput">
<!-- This field to be clicked when the id is populated. -->
<input type="button" name="submit" id="searchButton" value="Search" role="Search">
</div>
</body>
</html>
注意:奇怪的是,当我将Js手动输入到浏览器控制台中并将其输入到StackOverflow Code功能中时,Js可以很好地执行。 页面加载时,我只是无法获得运行的代码。