2012-01-04 68 views
0

我有以下代码完美的作品,但我需要一个onblur语句,如果用户点击离开下拉,因此把它回到它的原始状态 - 但试图实现这一点和不知道从哪里开始。如何onblur退出功能

下面的代码:

<script> 
$(document).ready(function(){ 
    var choices = "<select class='choices'>" 
        +"<option value='Choice 1'>Choice 1</option>" 
        +"<option value='Choice 2'>Choice 2</option>" 
        +"<option value='Choice 3'>Choice 3</option>" 
        +"<option value='Choice 4'>Choice 4</option>" 
        +"</select>"; 

    $(".update").click(function() { 
    var $this = $(this), 
     currentChoice; 
    // don't continue if there's already a select in this cell 
    if ($this.find("select").length != 0) 
     return; 
    currentChoice = $this.html(); 
    var $choices = $(choices); 
    $this.empty().append($choices); 
    $choices.val(currentChoice); 
    }); 

    $(document).on("change", ".choices", function() { 
    var $this = $(this); 
    $this.parent().html($this.val()); 
    return false; 
    }); 
}); 
</script> 

<table id="list"> 
    <tr> 
     <td>Film Name 1</td> 
     <td class="update">Choice 1</td> 
    </tr> 
    <tr> 
     <td>File Name 2</td> 
     <td class="update">Choice 3</td> 
    </tr> 
    <!-- etc --> 
</table> 

而且,我可以再使用onchange="this.form.submit();"提交变更到我的MySQL数据库?

回答

0

你的情况是有点棘手,从我所看到的,你没有选择,只能处理全球click事件文档,因为blur在我的测试中不像预期的那样对下拉元素有效。

因此,在全局点击事件中启动一个计时器,该计时器重置该值并在下拉本身的单击事件中及其父级单元取消计时器,以便用户仍可以选择。

必须添加的代码是:

var _timer = 0;  

$(document).on("click", ".choices, .update", function() { 
    window.clearTimeout(_timer); 
    return false; 
}); 

$(document).click(function() { 
    _timer = window.setTimeout(function() { 
     var oDDL = $(".choices"); 
     if (oDDL.length > 0) 
      oDDL.parent().html(oDDL.val()); 
    }, 50); 
}); 

Live test case

编辑:为了隐藏先前打开的下拉列表,你需要做的是,在单击事件:

$(document).on("click", ".choices, .update", function() { 
    window.clearTimeout(_timer); 
    var curDDL = $(this); 
    $(".choices").each(function() { 
     if (this !== curDDL.get(0) && this !== curDDL.find("select").get(0)) 
      $(this).parent().html($(this).val()); 
    }); 
    return false; 
}); 

Updated jsFiddle

+0

非常感谢这一点,那么最后一个难题是用户点击,这会关闭事件,这很好,如果用户点击选择2,它会关闭事件选择1?基本上这意味着每次只能打开一个选择框 - 我想这会使其结束 – 2012-01-04 10:56:53

+0

@Darren - 当然,请参阅我的编辑。 – 2012-01-04 12:03:27

0

是的,你可以在输入标签使用的onblur/onchange事件..表单元素中..

+0

我知道我可以,但问题是怎么样的...我猜它会在选择标签像onblur = *****买什么是*****谢谢 – 2012-01-04 09:57:28