我正在开发一个小部件,它对jQuery(幻灯片、淡出元素)有一些魔力。问题是,当我删除并替换侧栏中的小部件时,没有调用附加到小部件的jQuery脚本。
即使我在表单函数中有如下内容:
public function form( $instance ) {
wp_register_script(\'script\', get_template_directory_uri() . \'/script.js\', array(\'jquery\'), null, true);
wp_enqueue_script(\'script\');
}
脚本出现在页面中(如果我
view source 它就在那里)但是文件。未触发就绪功能,因此禁用所有onclick操作。
刷新页面可以解决问题,但有没有办法解决这个问题?
我需要这样的东西document.on("widget-attached-to-sidebar", function(){});
EDIT:
重现此问题的步骤:
refresh the page my jQuery script works delete the widget add it again my jQuery script is not working anymore (need to refresh the page again)
脚本。js仍在页面中(
view source) 通过所有这些步骤。
SO网友:Caspar
我认为最好的方式是根据小部件在页面上是否处于活动状态,使用检查有条件地加载脚本is_active_widget() widget类之外的其他地方并将其挂接到wp_enqueue_scripts. 类似这样:
function my_widget_load_js() {
if ( is_active_widget( false, false, (insert widget id-base here), true ) ) {
wp_register_script(\'script\', get_template_directory_uri() . \'/script.js\', array(\'jquery\'), null, true);
wp_enqueue_script(\'script\');
}
}
add_action ( \'wp_enqueue_scripts\', \'my_widget_load_js\' );
SO网友:mroncetwice
我不能因此而获得荣誉,但我必须与那些仍在寻找答案的人分享。。选择的答案在页面加载和小部件保存方面对我有效,但在小部件添加方面没有做任何事情,这是我工作所需要的。
再找了一会儿,我发现this answer 由用户提供,George, 我在我瞄准的特定小部件上进一步对其进行了定制:
var $_count = 0;
jQuery( document ).ajaxStop( function(){
var
$_saveBtns = jQuery(\'.widget-control-save\'),
$_yourSave = \'\';
$_saveBtns.each( function(){
if( jQuery(this).is(\'[id*="your-widget-id-string"]\') ){
$_yourSave = jQuery(this);
}
});
if ( $_count <= $_yourSave.length ){
/* Your script/function here */
$_count++;
}
else {
$_count = 0;
return;
}
});