如何制作自定义JavaScript选择器?



示例:

elementSelector('id')

我尝试了很多次:

function id(el) {
document.getElementById(el);
}

它不起作用。

使用名为id()的"便利函数"返回document.getElementById(el)

在这里,请注意返回

function id(el){
return document.getElementById(el);
}

我用一个例子来解释你的查询。

<button type="button" onclick="clickMe('demo')">change text in demo 1</button>
<button type="button" onclick="clickMe('demo2')">change text in demo 2</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
function clickMe(id){
document.getElementById(id).innerHTML='abcdef';
}
</script>
</body>
</html> 

在您的情况下,您需要整个对象,因此您应该返回函数将是

function clickMe(id){
return document.getElementById(id)
}

并称它将是

var demo=clickMe('demo');
demo.innerHTML='demo1';

您的函数正常,但缺少return关键字。如果你正在学习JavaScript,新的箭头函数语法可能会令人困惑。当只有一个表达式时,返回值,但是在块中(在{}中)时,您需要显式返回值:

const withImplicitReturn = id => document.getElementById(id);
const withExplicitReturn = id => { return document.getElementById(id); 
const returnsUndefined = id => { document.getElementById(id); }
function alsoReturnsUndefined(id) { document.getElementById(id); }
function returnsElement(id) { return document.getElementById(id); }

如果你打算相对于另一个元素使用你的辅助函数,我建议也提供父元素作为参数:

const getElementById = (parent, id) => parent ? parent.getElementById(id) : null;
// or function getElementByid(parent, id) { return parent ? parent.getElementById(id) : null; }

最新更新