为JavaScript制作一个简写函数

为JavaScript制作一个简写函数,javascript,html,Javascript,Html,我正在为内置JavaScript函数制作一个速记函数: function editById(getId) { document.getElementById(getId); } 然后我尝试在script.js中使用它: function run() { document.editById("test").style.color="blue"; } 然后我的HTML: <p id="test">TestTestestestse</p> <input typ

我正在为内置JavaScript函数制作一个速记函数:

function editById(getId) {
  document.getElementById(getId);
}
然后我尝试在script.js中使用它:

function run() {
  document.editById("test").style.color="blue";
}
然后我的HTML:

<p id="test">TestTestestestse</p>
<input type="button" onclick="run()" value="Change text color">
script.js

function run() {
  document.editById("test").style.color="blue";
}
function run2() {
  document.editByClass("test").style.color="blue";
}
function run3() {
  document.editByTag("h1").style.color="blue";
}
HTML

测试

testestse222

测试测试SE3685475
将函数修改为

function editById(getId) {
  //return object
  return document.getElementById(getId);
}

function run() {
  editById("test").style.color="blue";
}

此外,您还可以使用like

document.editById = function (getId) {
  return document.getElementById(getId);
}

function run() {
  document.editById("test").style.color = "blue";
}

将您的函数修改为

function editById(getId) {
  //return object
  return document.getElementById(getId);
}

function run() {
  editById("test").style.color="blue";
}

此外,您还可以使用like

document.editById = function (getId) {
  return document.getElementById(getId);
}

function run() {
  document.editById("test").style.color = "blue";
}

函数editById在文档对象上注册,但在窗口上注册。 不能这样调用函数

function run() {
  editById("test").style.color="blue";
}
您可以这样调用函数

function run() {
  editById("test").style.color="blue";
}

函数editById在文档对象上注册,但在窗口上注册。 不能这样调用函数

function run() {
  editById("test").style.color="blue";
}
您可以这样调用函数

function run() {
  editById("test").style.color="blue";
}

您在哪里定义了
document.editById
?您在哪里定义了
document.editById
?Ha,应该知道。非常感谢。或者,如果您想变得有趣,
var editById=document.getElementById.bind(document)
@Xero,
document.getElementsByTagName
随附返回具有给定标记名的元素的HTMLCollection。和
document.getElementsByClassName
将返回一组具有所有给定类名的元素。所以你必须使用像
document.editByClass(“test”)[0]
我会的,它一秒钟前还不允许我使用。再次感谢!哈,应该知道。非常感谢。或者,如果您想变得有趣,
var editById=document.getElementById.bind(document)
@Xero,
document.getElementsByTagName
随附返回具有给定标记名的元素的HTMLCollection。和
document.getElementsByClassName
将返回一组具有所有给定类名的元素。所以你必须使用像
document.editByClass(“test”)[0]
我会的,它一秒钟前还不允许我使用。再次感谢!我试过了,但没用@Satpal在我添加
返回时修复了它,我尝试了这个,但没有成功@Satpal在添加
返回时修复了它