附带的代码正确返回ID和复选框的值。 我需要获取封闭div的ID,以便可以将display属性设置为hidden。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="wrapper">
<form>
<div id="boatdiv1"><input type="checkbox" name="cb" id="boat1" value="123" onclick='doClick();'><label for='boat1'>boat1</label><br></div>
<div id="boatdiv2"><input type="checkbox" name="cb" id="boat2" value="456" onclick='doClick();' onclick='doClick();'><label for='boat2'>boat2</label><br></div>
<div id="boatdiv3"><input type="checkbox" name="cb" id="boat3" value="789" onclick='doClick();'><label for='boat3'>boat3</label><br></div>
</form>
</div>
</body>
<script>
function doClick() {
var checkedValue = null;
var inputElements = document.getElementsByName('cb');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
checkedID = inputElements[i].id;
console.log('checked id = '+checkedID);
console.log('value = '+checkedValue);
break;
}
}
ParentID = checkedID.offsetParent;
console.log(ParentID.id);
}
</script>
</html>
我希望ParentID将返回ID。相反,我收到错误消息“ TypeError:undefined不是对象(正在评估'ParentID.id')”
答案 0 :(得分:1)
您需要删除onevent属性,并改用onevent属性或事件侦听器:
<input
doClick()...>
基本上,这是隐藏单击元素(event.target
)的父元素所需要的:
event.target.parentElement.style.display = 'none';
演示中评论的详细信息
// Reference the form
var form = document.forms[0];
// Register the form to the change event
form.onchange = hide;
/*
Called when a user unchecks/checks a checkbox
event.target is always the currently clicked/changed tag
Get the changed parent and set it at display: none
*/
function hide(e) {
var changed = e.target;
changed.parentElement.style.display = 'none';
console.log(`Checkbox: ${changed.id}: ${changed.value}`);
console.log(`Parent: ${changed.parentElement.id}`);
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="wrapper">
<form>
<div id="boatdiv1"><input type="checkbox" name="cb" id="boat1" value="123"><label for='boat1'>boat1</label><br></div>
<div id="boatdiv2"><input type="checkbox" name="cb" id="boat2" value="456"><label for='boat2'>boat2</label><br></div>
<div id="boatdiv3"><input type="checkbox" name="cb" id="boat3" value="789"><label for='boat3'>boat3</label><br></div>
</form>
</div>
</body>
</html>
答案 1 :(得分:0)
使用parentNode
-还请注意checkedID
是一个字符串,因此它没有父级。使用getElementById
获取选中的输入:
ParentID = document.getElementById(checkedID).parentNode;
console.log(ParentID.id);