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

问题描述 投票:0回答:2

如果“ 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;
}

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

javascript jquery dom
2个回答
0
投票

所以是的,Jquery的目标是:少写,多做

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

这是您所能找到的所有方法中最少的一个。


0
投票

在这里挑毒

// 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>
© www.soinside.com 2019 - 2024. All rights reserved.