document.getElementById('phone').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
document.getElementById('phone-mobile-main').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
document.getElementById('phone-mobile-main').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
好的,所以我有这三个JS块,它们各自做同样的事情,我有它们的原因在我的页面上,我有3个表单,一个用于移动,一个用于模态弹出,一个用于幻灯片沿着右边。所有都有相同的形式。所以我想知道的是,有没有办法只做一个块,当用户选择它时,它只使用这个代码的一个块,而不是必须多次发布。我希望我解释这是有道理的。
答案 0 :(得分:1)
你可以做到
var elements = document.querySelectorAll('#phone, #phone-mobile-main');
if(elements.length > 0) {
elements.forEach(function(element){
element.addEventListener('input', function (e) {
var x = element.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
element.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
});
}

<input id="phone" type="text">
<input id="phone-mobile-main" type="text">
&#13;
这将涵盖您从上面显示的代码。
问题是:为什么移动和非移动设备有不同的ID。这没有多大意义。您应该考虑如何更改标记(HTML),因为它应该与移动设备和桌面相同。 Javascript和CSS只是其中的一层。
好的,所以我有三个JS块,它们各自做同样的事情, 我有他们的原因是在我的页面上,我有3个表格
另请注意,ID应该是唯一的。整个页面上的每个ID只能存在一次。如果它在模态窗口中也是如此。 (例外情况是,如果它们位于iframe中,再次作为一个页面处理)。你只有2个不同的id,但是说你有3个。
用另一个选择器做同样的事情
var elements = document.querySelectorAll('[data-phone="true"]');
if(elements.length > 0) {
elements.forEach(function(element){
element.addEventListener('input', function (e) {
var x = element.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
element.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
});
}
&#13;
<input data-phone="true" type="text">
<input data-phone="true" type="text">
&#13;
详细了解document.querySelector()和document.querySelectorAll(),您可以在其中选择类似document.querySelectorAll('.myClass')