测试"not null"并在JS中相应地设置值的紧凑方法



如果"x"为空,这当然会失败:

var x = document.getElementById('myElem');
x.value = "Hello";

当然,我们应该经常检查指针是否指向某个东西:(

var x = document.getElementById('myElem');
if (x)
x.value = "Hello";

现在,在纯JS甚至jQuery中(我无论如何都必须加载它,所以…(有没有办法做一些类似的事情

setIfExists('myElem', 'Hello');

是的,我会写

function setIfExists(el, v) {
var x = document.getElementById(el);
if (x)
x.value = v;
}

但我想知道这样的功能是否已经存在。谢谢

在这里挑选你的毒药

// fake it with new object if it is not there but creates an object
var y = document.getElementById('myElem') || {};
console.log(y); //logs {}
y.value = "Hello";
console.log(y); //logs {"value":"Hello"}
//jQuery, produce no error, logs undefined, c is 
//jQuery object that gets nothing assigned since 
//element does not exist so it is undefined
let c = $("#myElem").val("Cheers");
console.log(typeof c); // logs object 
console.log(c instanceof jQuery); // logs true
//console.log(c);// logs jQuery
console.log(c.jquery); // logs jQuery version "3.3.1"
console.log(c.val()); //undefined
let notthere = $("#myElem");
notthere.length || notthere.val("Howdy");
console.log(notthere.value); // undefined
// get the value only
let j = $("#myElem").value = "Woot";
console.log(typeof j, "j:", j); // string j: Woot
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

是的,Jquery的目的是:写得更少,做得更多

$("#myElem").val("Hello")

这是你能在所有现存的方法中找到的最起码的方法。

最新更新