javascript - 如何获取事件源元素

标签 javascript jquery function variables

我试图保持我的 JS 模块化,以便于可读性和通用性,但是我在获取 $(this) 时遇到了困难。 checkboxButton.on("click")的定义变量checkboxSelected .

如何在 function() 中创建全局变量(如果这是正确的放置方式)?

var checkboxButton = $("[data-checkbox-id]"),
    checkboxContainer = checkboxButton.parent();

function checkboxRadio() {

    var checkboxSelected = $(this).attr("data-checkbox-id");
    console.log(checkboxSelected);

    checkboxSelected.attr("aria-checked","true");

    if (!$('[data-checkbox-id="' + checkboxSelected +'"]')) {
        checkboxButton.attr("aria-checked","false");
    }
}


function checkboxInit() {
    console.log("Checkbox Initialised");

    checkboxButton.on("touchend click", function(e) {
        e.preventDefault();

        // Check the checkbox type
        if (checkboxContainer.attr("data-checkbox-type") == "radio") {
            checkboxRadio();
        } else {
            // checkboxMultiple();
        }
    });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset data-checkbox-type="radio">
    <label>Gender</label>
    <button class="checkbox-radio" value="male" name="male" aria-checked="true" data-checkbox-id="1">
        <span class="icon-checkbox"></span>
        No
    </button>
    <button class="checkbox-radio" value="female" name="female" aria-checked="false" data-checkbox-id="2">
        <span class="icon-checkbox"></span>
        Yes
    </button>
</fieldset>

最佳答案

在调用函数时发送this:

  1. checkboxRadio(this);
  2. 函数 checkboxRadio(btn) {
  3. var checkboxSelected = $(btn).attr("data-checkbox-id");

关于javascript - 如何获取事件源元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41388745/

相关文章:

r - 在 R 中创建一个用户创建的函数

php - 如何使用目录从 html 文件中获取标题 - php

javascript - 使用 jQuery 将所有 <audio> 元素静音

javascript - 如何修复未捕获的 InvalidValueError : setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

javascript - sencha touch 分机路由器

javascript - Jquery if 语句、选择器

Ajax - 阻止点击成功的 ajax 请求

javascript - IE6 中的 jquery 问题,有人吗?

python - 为什么这个问题发生在Python函数作用域中?

javascript - 我可以使用验证函数在 span id 标记内输出错误消息吗?