我正在创建一个库,并且试图创建一个可以在html脚本中调用的函数,该脚本可以为您创建基本元素。但是当我运行该函数时,我得到了一个错误。
createBasic = function(type, el) {
if(type === "title") {
let p = document.createElement("h1");
p.setAttribute("id", "title");
var current = document.getElementById(el);
document.body.insertBefore(p, current);
}
if(type === "p") {
let p = document.createElement("p");
p.setAttribute("id", "paragraph");
var current = document.getElementById(el);
document.body.insertBefore(p, current);
}
if(type === "div") {
let p = document.createElement("div");
p.setAttribute("id", "div container");
var current = document.getElementById(el);
document.body.insertBefore(p, current);
}
return self;
};
//function being called
$x("#stuff").createBasic("title");
我希望它根据类型来创建一个元素,但是我得到了
未捕获的TypeError:$ x(...)。createBasic不是base.html:19处的函数
答案 0 :(得分:0)
如果要为对象添加类似静态的方法,则可以
const $x = selector => ({ // create a object
createBasic: () => "created something for " + selector, // add methods
})
console.log($x("#id").createBasic())
您的情况将是
const $x = selector => ({
createBasic: function(type, el) {
if (type === "title") {
let p = document.createElement("h1");
p.setAttribute("id", "title");
p.innerHTML = "title"
var current = document.getElementById(el);
document.body.insertBefore(p, current);
}
if (type === "p") {
let p = document.createElement("p");
p.setAttribute("id", "paragraph");
var current = document.getElementById(el);
document.body.insertBefore(p, current);
}
if (type === "div") {
let p = document.createElement("div");
p.setAttribute("id", "div container");
var current = document.getElementById(el);
document.body.insertBefore(p, current);
}
return self;
}
})
//function being called
$x("#stuff").createBasic("title");
此外,此处未使用$x
的参数,要使用它们,只需引用内部的选择器变量,因为这是元素选择器
以这种方式出现的东西,或者您称其为jquery风格的
const $x = selector => ({
turnColor: (color) => document.querySelector(selector).style.color = color
})
$x("div").turnColor("red")
<div>okay<div>