获取.closest()div id

时间:2013-12-02 11:17:10

标签: javascript jquery html

我正在尝试实现this answer中给出的代码。我想进一步简化它,使用closest()查找最近id的{​​{1}}并将其用作位置,但它不起作用 - 我只是得到'未定义'在我的文本框中。

这是脚本:

div

这是(简化)标记:

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);
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

HTML中的

你需要通过this

<div id="Philadelphia">
 <a href="javascript:updateDetails('20-24 January',this);">20-24 January</a>
</div>

IN JS

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);
            }

并且通过jquery,您可以通过以下非常简单的方式

现在使用html

<div id="Philadelphia">
    <a href="#">20-24 January</a>
</div>

在JS中

$("#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);
});
相关问题