javascript 在 Jquery 中手动触发事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11618367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:49:38  来源:igfitidea点击:

Manually fire event in Jquery

javascriptjquery

提问by ist_lion

I am dynamically creating a list of input boxes in JQuery and have an event to notify me when they are checked.

我正在 JQuery 中动态创建输入框列表,并在检查它们时有一个事件通知我。

$("#myDiv").on("change",  "input[type='checkbox']" , function(){
   if(this.checked){
     alert("HERE");
     //...
   }else{
    alert("THERE");
    //...
   }
});

When the page loads and all the checkboxes show - I can have this enter by checking/unchecking. The problem is that I want a few of these to be checked initially depending on the results of my backend logic. So I want to enter this function after the initial load.

当页面加载并显示所有复选框时 - 我可以通过选中/取消选中来输入。问题是我希望根据后端逻辑的结果最初检查其中的一些。所以我想在初始加载后进入这个功能。

I looked at .trigger()and .click()however, neither seem to do the trick.

我看了看.trigger(),并.click()然而,无论似乎做的伎俩。

Is there another avenue I could take to enter this callback?

我还有其他途径可以进入这个回调吗?

采纳答案by JJJ

In this case you can create a named function instead of using an anonymous one and call it whenever you need.

在这种情况下,您可以创建一个命名函数而不是使用匿名函数,并在需要时调用它。

var myFunction = function(){
   if(this.checked){
     alert("HERE");
     //...
   }else{
    alert("THERE");
    //...
   }
}

$("#myDiv").on("change", "input[type='checkbox']", myFunction );

// triggering the function manually:
$("#myDiv input[type='checkbox']").each( myFunction );

回答by Jashwant

If you want to show checked on a checkbox, just set checkedproperty to checked

如果要在复选框上显示选中状态,只需将checked属性设置为checked

<input type='checkbox' checked='checked' />

If you want to fire change();event,

如果你想触发change();事件,

$('<your_checkbox>').change(); 

or

或者

$('<you_checkbox>').trigger('change');

回答by Frenchi In LA

your code is triggered when myDiv is changing, and you pass a list of checkbox. here 'this' is the mydiv. why not using:

当 myDiv 更改时触发您的代码,并且您传递了一个复选框列表。这里的'this'是mydiv。为什么不使用:

$('input:checkbox').each(function(){// Now this is referring your checkbox});

回答by Dave F

Define your function separately by name and then call it after the page has loaded for each item that has been checked off.

按名称分别定义您的函数,然后在为每个已选中的项目加载页面后调用它。

function onChange(this) {
    if(this.checked){
        alert("HERE");
        //...
    }else{
        alert("THERE");
        //...
    }
}

Your code that monitors checkbox changes would become:

您监视复选框更改的代码将变为:

$("#myDiv").on("change",  "input[type='checkbox']" , function() {
    onChange(this);
});

Since I don't know what the code looks like, I've written some code to print check boxes and define which ones are to be selected by default. It is PHP, but the concept should work for any server side language.

由于我不知道代码是什么样的,我写了一些代码来打印复选框并定义默认情况下要选中哪些复选框。它是 PHP,但这个概念应该适用于任何服务器端语言。

<select>
<?php
$items = array(
    'value1' => 'text1',
    'value2' => 'text2',
    'value3' => 'text3'
);

$selected = array(
    'value1' => true,
    'value3' => true
);

foreach ($items as $value => $text) {
    $selectedAttr = isset($selected[$value]) && $selected[$value]) ?
        " selected='selected'" : '';
    echo "<option value='$value'$selectedAttr>$text</option>";
}
?>
</select>

You'll need to print javascript that runs the function that you want to have executed for each selected option. For the checkbox example that I used, the end result that you'd want is:

您需要打印运行您希望为每个选定选项执行的函数的 javascript。对于我使用的复选框示例,您想要的最终结果是:

$().ready(function() {
    var defaultSelected = [ "[option name='value1']" , "[option name='value3']" ];

    for (var i=0; i < defaultSelected.length; i++) {
        $(defaultSelected[i]).each(onChange);
    }
});

You'll need to generate the javascript on the server side:

您需要在服务器端生成 javascript:

<?php

// $selected was defined in the previous code section

// Create selectors that will select each checkbox option
$selectors = array();
foreach ($selected as $s) {
    array_push($selectors, "[option name='$s']");
}

// Produces string: [ "[option name='value1']" , "[option name='value3']" ]
$jsSelectorArray = '[ "' . implode('" , "', $selectors) . '" ]';

echo "
$().ready(function() {
    var defaultSelected = $jsSelectorArray;

    for (var i=0; i < defaultSelected.length; i++) {
        $(defaultSelected[i]).each(function() {
            onChange(this);
        });
    }
});
";

?>