Javascript 获取最近的()div id
我正在尝试实现中给出的代码。我想通过使用Javascript 获取最近的()div id,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试实现中给出的代码。我想通过使用closest()查找最近的div的id并将其用作位置来进一步简化它,但它不起作用-我只是在文本框中得到了“undefined” 以下是脚本: function updateDetails(date) { var loc = $(this).closest("div").attr("id"); $('#buy-form').animatescroll({scrollSpeed:700,easing:'easeInOutSine'});
closest()
查找最近的div
的id
并将其用作位置来进一步简化它,但它不起作用-我只是在文本框中得到了“undefined”
以下是脚本:
function updateDetails(date) {
var loc = $(this).closest("div").attr("id");
$('#buy-form').animatescroll({scrollSpeed:700,easing:'easeInOutSine'});
document.getElementById('date').value= date;
document.getElementById('venue').value= loc;
$('#resicheck').attr('disabled', true);
}
以下是(简化的)标记:
我做错了什么?在HTML中 您需要通过
此
<div id="Philadelphia">
<a href="javascript:updateDetails('20-24 January',this);">20-24 January</a>
</div>
通过jquery,您确实喜欢下面非常简单的方式
现在为html格式
<div id="Philadelphia">
<a href="#">20-24 January</a>
</div>
在href属性中?-它可以工作,因为它更新了日期输入。你确定,$(this)
是你期望的吗?@Syjin nope,我怎么能检查?我已经试着用'a'
@elendilth替换这个
,您可以使用…控制台进行检查此
引用窗口对象,因为href不创建任何函数closure@elendilthetall您可以使用console.log(this)
将其记录到控制台。我想疯人院的答案对你来说应该很好。。。
function updateDetails(date,this) {
var loc = $(this).closest("div").attr("id");
$('#buy-form').animatescroll({scrollSpeed:700,easing:'easeInOutSine'});
document.getElementById('date').value= date;
document.getElementById('venue').value= loc;
$('#resicheck').attr('disabled', true);
}
<div id="Philadelphia">
<a href="#">20-24 January</a>
</div>
$("#Philadelphia").on("click","a",function(e){
e.preventDefault();
var date=$(this).text();
var loc = $(this).closest("div").attr("id");
$('#buy-form').animatescroll({scrollSpeed:700,easing:'easeInOutSine'});
$('#date').val(date);
$("#venue").val(loc);
$('#resicheck').attr('disabled', true);
});