可以将 document.querySelector('.xm-country-select') 缓存到一个变量中,避免每次都要重新查找 DOM 元素。同时,可以使用更加简洁的 ES6 语法来遍历 items 数组,使用 find() 方法查找 code.textContent 为 '+1' 的元素,并使用可选链运算符 ?. 来避免 code 不存在的情况。

const countrySelect = document.querySelector('.xm-country-select');
countrySelect.style.display = 'block';

const items = document.querySelectorAll('.list-view-item');
const targetItem = [...items].find(item => item.querySelector('.code')?.textContent === '+1');
if (targetItem) {
  targetItem.querySelector('.code').click();
}

通过以上优化,代码更加简洁高效,也更容易理解和维护。

JavaScript DOM 操作优化:提高代码效率和可读性

原文地址: https://www.cveoy.top/t/topic/lHKd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录