我试图保持我的 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
:
checkboxRadio(this);
函数 checkboxRadio(btn) {
var checkboxSelected = $(btn).attr("data-checkbox-id");
关于javascript - 如何获取事件源元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41388745/