[英]translate jQuery to pure javascript
I have to fix some form validation but there's no jQuery included in the host page. 我必须修复一些表单验证,但主页中没有包含jQuery。 I'd normally do something like this...
我通常会这样做......
if ($("#contactNameAdd").val() !== '' || $("#contactPhoneAdd").val() !== '') {
$("#contactForm").show()
};
How can I re-write that in normal js? 我怎样才能在普通的js中重写它?
var name = document.getElementById("contactNameAdd");
var phone = document.getElementById("contactPhoneAdd");
var form = document.getElementById("contactForm");
if(name.value != '' || phone.value != '') {
form.style.display = "block";
}
if (document.getElementById('contactNameAdd').value !== '' || document.getElementById('contactPhoneAdd').value !== '') {
document.getElementById('contactForm').style.display = 'block';
}
In plain javascript, you use document.getElementById('id') to get DOM nodes based on the id attribute. 在普通的javascript中,您使用document.getElementById('id')来基于id属性获取DOM节点。 You use
.value
on a DOM Input element to get its value. 您在DOM Input元素上使用
.value
来获取其值。 And you use .style
on any DOM element to set css attributes. 并且您在任何DOM元素上使用
.style
来设置css属性。 In this case "show" means "display: block;". 在这种情况下,“show”表示“display:block;”。
if (document.getElemenById('contactNameAdd').value != '' || document.getElementById('contactPhoneAdd').value != '') {
document.getElementById('contactForm').style.display = 'block';
}
Try this - checks the 2 values then changes the style.display property of the 'contactForm' 试试这个 - 检查2个值然后更改'contactForm'的style.display属性
This should do the trick. 这应该可以解决问题。
var contactNameAdd = document.getElementById("contactNameAdd");
var contactPhoneAdd = document.getElementById("contactPhoneAdd");
if((contactNameAdd !== null && contactNameAdd.value !== '') || (contactPhoneAdd !== null && contactPhoneAdd.value !== ''))
{
document.getElementById("contactForm").style.display = 'block';
}
var contactName = document.getElementById('contactNameAdd');
var contactPhone = document.getElementById('contactPhoneAdd');
if(contactName.value !== '' || contactPhone.value !== '') {
// Different as JQuery, there will be no animation.
// I assume you use 'display:none' to hide the form.
var form = document.getElementById('contactForm');
form.style.display = 'block';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.