在JS Helper CakePHP中手动触发事件

Aru*_*ain 6 cakephp cakephp-2.1 cakephp-2.2 ajaxhelper

我陷入困境.我正在使用JS Helper.我使用了以下代码.

<?php $this->Js->get('#client_id')
        ->event('change', $this->Js->request(array('action' => '../ajax/get_client_location_and_process'),
                   array('update' => '#client_location_process',
                     'async' => false, 
                     'dataExpression' => true,
                     'method' => 'post',
                     'evalScripts' => true,
                     'data' => $this->Js->serializeForm(array('isForm' => True, 'inline' => True))
                     )
                   )
        );
Run Code Online (Sandbox Code Playgroud)

我想在页面加载时触发更改事件.如果我使用document.ready方法,那么它无法正常工作.我无法找到JS Helper方法,我们可以在控件上显式触发一些事件.请建议代码如何在需要时在表单元素上执行类似JQuery trigger()的功能.

uzy*_*zyn 13

既然你已经.trigger()在jQuery中发现了,你可以将它与你的视图代码一起使用:

<?php 
    // Your view code
?>
<script>$('#client_id').trigger('change');</script>
Run Code Online (Sandbox Code Playgroud)

或者,如果你仍然喜欢通过PHP来做,你可以自己创建帮手,例如:

<?php 
class ArunjsHelper extends AppHelper {
    public $helpers = array('Html');

    function trigger($element, $event, $options = array()) {
        return $this->Html->scriptBlock("$('$element').trigger('$event');");
    }
}
Run Code Online (Sandbox Code Playgroud)

添加ArunjsHelper$helpers控制器:

<?php
class SomeController extends Controller {
    public $helpers = array('Arunjs');

    // Your controller code
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以从视图中调用它:

<h1>Hello</h1>
<p>Your usual view HTML code</p>

<?php // Trigger the change event ?>
<?php echo $this->Arunjs->trigger('#client_id', 'change'); ?>
Run Code Online (Sandbox Code Playgroud)