javascript - 将 jquery 转换为纯 javascript 函数
问题描述
我正试图让自己放弃对几个项目使用 jQuery。下面是一个简单的例子,但我想用它来看看如何将它转换为非 jQuery、vanilla javascript:
$(function () {
console.log('jQuery is working.')
updateBillingSection();
$('select').on('change', function() {
updateBillingSection();
});
function updateBillingSection() {
// (1) If the plan is not of type=BUSINESS or INDIVIDUAL, hide the billing section
var INDIVIDUAL_PLAN = "INDIVIDUAL";
var BUSINESS_PLAN = 'BUSINESS'
var paidPlans = [INDIVIDUAL_PLAN, BUSINESS_PLAN]
var planType = $('select[name="plan_type"] option:selected').val();
console.log('Plan type: ' + planType);
if(paidPlans.includes(planType)) {
$('.paid-plan-details').show("slow");
} else {
$('.paid-plan-details').hide("slow");
}
}
}
我的问题有两个:
- 上面有什么方法可以改进代码吗?
- 在不加载 jquery 的情况下,上面的内容如何用 javascript 编写?
解决方案
在 jquery 中使用 CSS 选择器进行选择$('.paid-plan-details')
变成document.querySelector('.paid-plan-details')
获得价值$('select[name="plan_type"] option:selected').val()
变成document.querySelector('select[name="plan_type"] option:selected').value
$('select').on('change', function() {})
变成document.querySelector('select').onchange = function() {}
一些指向正确方向的指针。查看所有详细信息的文档:https ://developer.mozilla.org/en-US/docs/Web/API/Document