我有这个函数代码,我正在用javascript创建一个代码片段。我想知道我是否可以让它看起来更好,因为我认为我做的这段代码看起来并不专业。
我试着使用反结构,但由于某些原因,我的浏览器向我显示了这样一条消息:Uncaught TypeError: 无法读取未定义的'appendChild'属性。
我想知道,在javascript中,是否有更好的方法将多个参数传递给函数,并将参数作为一个对象文字发送?还有为什么说字符串包含无效字符?
非常感谢。
const create = function ({t, v, p}) {
let n = document.createElement(t);
n.innerHTML = v;
p.appendChild(n);
return n;
};
// create the list for reference
let ul = create({
t: 'ul',
v: null,
p: document.body
});
下面是完整的JS代码。
const createsnippets = function (e) {
// the reference node -- we atually have one ID for headlines
let headlines = document.getElementById('headlines');
// utility function to add new HTML DOM element
const create = function ({t, v, p}) {
let n = document.createElement(t);
n.innerHTML = v;
p.appendChild(n);
return n;
};
// create the list for reference
let ul = create({
t: 'ul',
v: null,
p: document.body
});
// find all newsarticle classess and add then to snippet in sequence
Array.from(document.querySelectorAll('article.newsarticle > h4')).forEach(function (h4) {
create('li', h4.textContent + ' ... ' + h4.nextElementSibling.innerText, ul);
});
// insertion re-factors HTMl to ensure the layout (markup and CSS) when displaed
headlines.parentNode.insertBefore(ul, headlines.nextSibling)
}
// once prepared, we can display the loaded content as snippet/collection
document.addEventListener('DOMContentLoaded', createsnippets);
你的参数重构很好,但你调用的是 create
以两种不同的方式。这个电话没问题......但这个就不行了:
let ul = create({
t: 'ul',
v: null,
p: document.body
});
...但这个不行
create('li', h4.textContent + ' ... ' + h4.nextElementSibling.innerText, ul);
这将会导致你的创建函数试图反构筑一个 t
, v
和 p
财产 从字符串 'li'
. 解构代码大致翻译成这样,下面是第二个调用的结果。
function(param) { // param = 'li'
let t = param.t; // t = 'li'.t -> t = undefined
let v = param.v; // v = 'li'.v -> v = undefined
let p = param.p; // p = 'li'.p -> p = undefined
let n = document.createElement(t); // n = document.createElement(undefined)
n.innerHTML = v;
p.appendChild(n); // undefined.appendChild(n)
return n;
}
也许你的意思是:
create({
t: 'li',
v: `${h4.textContent} ... ${h4.nextElementSibling.innerText}`,
p: ul
});