如何将给定jQuery代码转换为简单的原生Vanilla JavaScript代码?
jQuery代码转原生Vanilla JavaScript实现
以下是和原逻辑完全等价的原生JS实现,无需依赖jQuery:
<script> /*<![CDATA[*/ const pwdLink = document.querySelector('a#password_here'); if (pwdLink) { pwdLink.setAttribute('href', 'url_here'); pwdLink.textContent = 'password_here'; pwdLink.setAttribute('style', 'visibility:visible!important;opacity:1!important;position:relative!important;z-index:1!important;font-size:14px!important;color:#fff!important;'); } setInterval(function () { if (!document.getElementById('password_here')) { window.location.href = 'url_here' } }, 1000) /*]]>*/ </script>
转换对应规则
- 元素选择:jQuery的
$('选择器')对应原生document.querySelector('选择器'),纯id选择场景用document.getElementById('id值')性能更优 - 属性设置:jQuery的
.attr(属性名, 属性值)对应原生Element.setAttribute(属性名, 属性值)方法 - 文本设置:jQuery的
.text(文本内容)对应原生给Element.textContent属性直接赋值 - 元素存在判断:jQuery通过
.length判断是否选中元素,原生直接判断DOM查询方法的返回值是否为null即可,判断逻辑完全等价 - 页面跳转逻辑
window.location.href是浏览器原生API,和原jQuery写法一致无需修改
提示:实际使用时请将代码中
url_here、password_here两个占位符替换为你真实的跳转地址、密码显示文本。
内容的提问来源于stack exchange,提问作者Nee Heper
相关产品推荐
相关产品推荐

