[英]Run Jquery code once on page load
我有2個表單字段(十六進制顏色),當用戶單擊它們時會激活它們。
如果用戶正在編輯現有數據集,那么在加載頁面時,我將加載顏色並將其顯示在字段中。 加載頁面后如何運行腳本,以便在字段旁邊顯示正確的顏色?
那么如何在頁面加載時運行$('#colorpicker1').colpick()
和$('#colorpicker2').colpick()
?
我正在運行的腳本是http://colpick.com/plugin (示例1,但是在頁面加載時字段中的數據已經為“ READY”)
謝謝
$(document).ready(function (){
$('#colorpicker1').colpick({
layout:'hex',
submit:0,
onChange:function(hsb,hex,rgb,el,bySetColor) {
$(el).css('border-color','#'+hex);
// Fill the text box just if the color was set using the picker, and not the colpickSetColor function.
if(!bySetColor) $(el).val(hex);
}
}).keyup(function(){
$(this).colpickSetColor(this.value);
});
$('#colorpicker2').colpick({
layout:'hex',
submit:0,
onChange:function(hsb,hex,rgb,el,bySetColor) {
$(el).css('border-color','#'+hex);
// Fill the text box just if the color was set using the picker, and not the colpickSetColor function.
if(!bySetColor) $(el).val(hex);
}
}).keyup(function(){
$(this).colpickSetColor(this.value);
});
});
$(window).load(function(){
$('#colorpicker1, #colorpicker2').colpick()
});
嘗試這個:
請參閱所引用的插件,用於顏色選擇器的JS和CSS已從您鏈接的站點中獲取。
http://plnkr.co/edit/nYSY6b7JJwdHXJ7SmcdP?p=preview
理想情況下,這種模式可以解決您的問題-
<script>
$(function(){
$(".className").colpick({
/*
Inner Code.
*/
});
});
</script>
編輯:好的,所以您的問題與插件無關。 看看更新的plunker- http://plnkr.co/edit/nYSY6b7JJwdHXJ7SmcdP?p=preview
$.each($('.colorpicker'),function(){
$(this).css('background','#'+$(this).val());
});
這將解決您的問題,因為該插件沒有可用的任何方便的方法/選項。
編輯-最終解決方案
要加載輸入字段中已經存在的顏色並正確激活腳本,請執行以下操作:
$.each($('.colorpicker'),function(){
//init code
var defCol = $(this).val();
$(this).css('border-color','#'+defCol);
//plugin
$(this).colpick({
layout:'hex',
submit:0,
color: defCol,
onChange:function(hsb,hex,rgb,el,bySetColor) {
$(el).css('border-color','#'+hex);
// Fill the text box just if the color was set using the picker, and not the colpickSetColor function.
if(!bySetColor) $(el).val(hex);
}
}).keyup(function(){
$(this).colpickSetColor(this.value);
});
});
$( document ).ready()
是您需要的。
使用這種方式:
$( document ).ready(function(){
// the document is ready now, do stuff here
});
jQuery給出onload或現成的功能以在加載時執行腳本-
$(document).ready(function(){
alert("document ready occurred!");
});
$(window).load(function(){
alert("window load occurred!");
});
准備使用文檔時要執行一些功能:
$(document).ready(function(){
$('#colorpicker1').colpick()
$('#colorpicker2').colpick()
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.