[英]Transform jQuery function to pure JavaScript
如何將用JQuery編寫的代碼轉換為JS?
原始代碼:
$('.abcClass').each(function () {
$(this).html($(this).text().replace(/([^\x00-\x80]|\w)/g, "<span class='mail'>$&</span>"));
});
我試着這樣寫:
document.querySelectorAll('.abcClass').forEach(function (comment) {
comment.innerHTML(comment.toString().replace(/([^\x00-\x80]|\w)/g, "<span class='mail'>$&</span>"));
});
但是我收到了錯誤:
Uncaught TypeError: comment.innerHTML is not a function
Uncaught TypeError: Cannot read property 'classList' of null
我是jQuery的新手,所以我發現自己在這一步幾乎陷入了困境...任何幫助將不勝感激! :)
雖然.innerHTML
是其下的函數,但它是一個setter(和getter),因此您必須像設置普通屬性值一樣設置和檢索其值:
comment.innerHTML = comment.innerHTML
.replace(/([^\x00-\x80]|\w)/g, "<span class='mail'>$&</span>"));
還要記住, querySelectorAll
返回一個NodeList,而NodeLists在較新的瀏覽器(2016年中左右)中僅具有forEach
方法。 為了獲得更好的向后兼容性,請考慮調用Array.prototype.forEach
:
Array.prototype.forEach.call(
document.querySelectorAll('.abcClass'),
function(comment) {
// ...
(當然,您也可以事先執行NodeList.prototype.forEach = Array.prototype.forEach
,但這對我來說真的很奇怪)
而不是使用jquery .each()
$('div').each(function(){ //... })
使用document.querySelectorAll(),然后將HTMLCollection轉換為JavaScript數組。 然后,您可以映射元素數組。
const elems = document.querySelectorAll('.my-elements')
const $elems = [].slice.call(elems)
$elems.map( (elem) => { console.log(elem) })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.