我有一小段 JavaScript 代码用作用户脚本。该操作运行良好,但我想向其中添加 if 语句,但不知道如何构建它。
用简单的语言,我希望它这样做:
或者交替
这是如何实现的?我在摆弄
document.querySelectorAll
但到目前为止没有运气。
document.querySelector
来检查是否存在。
if (!document.querySelector('input[type=password]')) {
// your code here
}
尝试将此查询与
document.querySelector()
一起使用:input[type="password"]
。如果你没有得到结果,它会返回null
,你知道它不存在于页面上。
然后您可以使用它通过返回来结束用户脚本。
这里有两个例子(相同的 JS,第一个有密码,第二个没有):
(function(){
if (document.querySelector('input[type="password"]') !== null) {
return;
}
console.log('userscript');
})();
<input type="text">
<input type="password">
(function(){
if (document.querySelector('input[type="password"]') !== null) {
return;
}
console.log('userscript');
})();
<input type="text">