将 HTML 元素传递给 JavaScript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26796528/
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-28 06:30:13  来源:igfitidea点击:

Pass HTML element to JavaScript function

javascriptjqueryhtml

提问by kat1330

I am passed 3 html elements as parameters to JS function. JS function is in separate file. I have problem to bind 'click' event with _confBtn object (which is parameter). My complete JS file:

我将 3 个 html 元素作为参数传递给 JS 函数。JS 函数在单独的文件中。我有问题将 'click' 事件与 _confBtn 对象(这是参数)绑定。我的完整 JS 文件:

 window.HAS = window.HAS || {};
HAS.MyApp = HAS.MyApp || {};

(function (_this, $, undefined) {
var _sessionTimeOut = false;
var _startCountDown = false;
var _counterTime;
var _countDownTime;
var _dialogWrap;
var _confBtn;
var _counter;

_this.init = function (showDialogTime, logofCountDownTime, dialogWrap, counter, confirmationButton) {

    _counterTime = 5;
    _countDownTime = 0;
    _dialogWrap = $('#' + dialogWrap);
    _confBtn = $('#' + confirmationButton);
    _counter = $('#' + counter);
    alert(_confBtn.text());
    createSessionTimeOut();
    $(document).bind("mousemove keypress mousedown mouseup", resetTimeOut);
}

_confBtn.on('click', function () {
    window.clearInterval(_startCountDown);
    _dialogWrap.css('visibility', 'hidden');
    createSessionTimeOut();
    $(document).bind("mousemove keypress mousedown mouseup", resetTimeOut);
});

function createSessionTimeOut() {
    _sessionTimeOut = window.setTimeout(function () {

        _dialogWrap.removeAttr("style");
        _counter.text(_counterTime);
        $(document).unbind("mousemove keypress mousedown mouseup");

        startCountDown();
    }, 2000);
}

function startCountDown() {
    _startCountDown = window.setInterval(function () {
        if (_counterTime >= 0) {
            _counter.text(_counterTime--);
        }
        _countDownTime++;
        if (_countDownTime >= 4) {
            logOutUser();
            return;
        }

    }, 1000);
}

function resetTimeOut() {
    window.clearTimeout(_sessionTimeOut);
    _sessionTimeOut = false;
    createSessionTimeOut();
}

function logOutUser() {
    $.ajax({
        url: '/MyApp/Account/LogOut',
        type: 'GET',
        success: function () {
            document.location.href = '/MyApp/Account/Login';
        }
    })
}

}(window.HAS.MyApp.SessionTimeOut = window.HAS.MyApp.SessionTimeOut || {}, jQuery));

I call in separate page like in following:

我调用单独的页面,如下所示:

SessionTimeOut.init('5', '5', 'dialog-wrap', 'confirm-button', 'counter');

I have issue with _confBtn when I try to call click event. Browser show that is undefined.

当我尝试调用 click 事件时,我遇到了 _confBtn 问题。浏览器显示未定义。

Please help.

请帮忙。

回答by Stu

It would probably better to do something more dynamic like this:

做一些更动态的事情可能会更好:

function SomeFunction (element1,element2) {
    var e1 = $("#"+element1),
        e2 = $("#"+element2);
    // Do something with variables e1 and e2
}

and you would call like this:

你会这样调用:

//html:
<div id="one"><div>
<div id="two"><div>

//javasctript:
SomeFunction('one','two');

回答by Terry

You can of course do it, just by using the normal jQuery way of including multiple selectors. Your code is slightly incorrect because you are actually only defining the function without calling it, and you are not supposed to pass arguments/variables into the function when defining it.

您当然可以这样做,只需使用包含多个选择器的普通 jQuery 方式即可。您的代码有点不正确,因为您实际上只是定义了函数而不调用它,并且在定义它时不应该将参数/变量传递给函数。

Unless you have the intention to distinguish between two groups of elements, I would refrain from declaring elements individually as you have used in your question, because sometimes you will never know the length of the selected items.

除非您打算区分两组元素,否则我不会像您在问题中使用的那样单独声明元素,因为有时您永远不会知道所选项目的长度。

function someFunction($ele) {
    // jQuery objects will be accessible as $ele
}

// Call the function
someFunction($('#selector1, #selector2'));

However, if the former is the case, you can always do so:

但是,如果是前者,您始终可以这样做:

function someFunction($ele1, $ele2) {
    // jQuery objects will be accessible as $ele1 and $ele2 respectively
    // Example: $ele1.hide();
    //          $ele2.show();
}

// Call the function
someFunction($('#selector1'), $('#selector2'));

For example, you can refer to this proof-of-concept JSfiddle: http://jsfiddle.net/teddyrised/ozrfLwwt/

例如,你可以参考这个概念验证 JSfiddle:http: //jsfiddle.net/teddyrised/ozrfLwwt/

function someFunction($ele) {
    // jQuery objects will be accessible as $ele
    $ele.css({
        'background-color': '#c8d9ff'
    });
}

// Call the function
someFunction($('#selector1, #selector2'));

回答by Krzysiek

If you want to pass some elements to function you can use jQuery constructor to standardize arguments

如果你想将一些元素传递给函数,你可以使用 jQuery 构造函数来标准化参数

function SomeFunction (element1,element2) {
    element1 = $(element1);
    element2 = $(element2);
    // and you have 2 jQuery objects...
}

// and now you can pass selector as well as jQuery object.
SomeFunction($('div.a'),'#b');

回答by Peter Herdenborg

No, you are mixing a function declaration with a function call somehow. You can't provide function arguments when defining a function. This however will work fine:

不,您以某种方式将函数声明与函数调用混合在一起。定义函数时不能提供函数参数。但是,这将正常工作:

function someFunction($element1, $element2) {
    //Do something with the elements
}

someFunction($("#element1"), $("#element2"));

Note that $element1and $element2are just variable names, and the leading $ doesn't have anything to do with jQuery. It is just a common convention to identify variables referencing jQuery selections.

请注意,$element1and$element2只是变量名,前导 $ 与 jQuery 没有任何关系。标识引用 jQuery 选择的变量只是一个常见的约定。