
Ini adalah kombinasi dari kode yang Saya temukan di sini dan juga kode yang pernah Saya dokumentasikan di sini. Meskipun kita bisa menggunakan fungsi .textWalk()
berkali-kali seperti ini:
jQuery.fn.textWalk = function(fn) {
this.contents().each(jwalk);
function jwalk() {
var nn = this.nodeName.toLowerCase();
if (nn === '#text') {
fn.call(this);
} else if (this.nodeType === 1 && this.childNodes && this.childNodes[0] && nn !== 'script' && nn !== 'textarea') {
$(this).contents().each(jwalk);
}
}
return this;
};
$('body').textWalk(function() {
this.data = this.data.replace('Lorem', 'Love');
this.data = this.data.replace('consequat', 'consequence');
this.data = this.data.replace('at vero', 'at the shop');
this.data = this.data.replace('nihil', 'ZERO man... ZEROO!!!');
this.data = this.data.replace('click me', 'Mamamiaaa!!!');
this.data = this.data.replace('My Blog', 'My Kingdom');
});
Tapi seandainya kita bisa membuatnya lebih pendek, seharusnya ini akan menjadi lebih efisien seperti yang pernah dikatakan oleh seseorang dengan nama pengguna gilly3:
You need to use a regular expression with the global option set to replace all of the instances. But, you can also simplify this code a bit and get rid of the loop. Instead of Arrays, use an object - Stackoverflow
Anda perlu menggunakan regex dengan opsi global yang ditetapkan untuk menggantikan semua contoh. Tapi, Anda juga dapat menyederhanakan kode ini sedikit dan menyingkirkan loop. Dibandingkan menggunakan Array
, gunakanlah object
.
Saya tidak begitu mengerti dengan jelas mengenai istilah-istilah itu :p Saya hanya mencoba mengombinasikan dua artikel itu dan ternyata berhasil!
var array = {
"Lorem" : "Love",
"consequat" : "consequence",
"at vero" : "at the shop",
"nihil" : "ZERO man... ZEROO!!!",
"click me" : "Mamamiaaa!!!",
...
...
...
...
...
...
...
"My Blog" : "My Kingdom"
}
jQuery.fn.textWalk = function(fn) {
this.contents().each(jwalk);
function jwalk() {
var nn = this.nodeName.toLowerCase();
if (nn === '#text') {
fn.call(this);
} else if (this.nodeType === 1 && this.childNodes && this.childNodes[0] && nn !== 'script' && nn !== 'textarea') {
$(this).contents().each(jwalk);
}
}
return this;
};
$('body').textWalk(function() {
for (var val in array) {
this.data = this.data.replace(new RegExp(val, "g"), array[val]);
}
});
0 comments:
Post a Comment