点击功能不响应包装的范围标记

时间:2015-05-31 10:34:33

标签: javascript jquery html

我正在尝试在输入字段和文本字段之间切换。 如果我只在span标签上进行,那么它可以正常工作。但是,如果将span标记包装为表数据,则它不会响应。

任何帮助将不胜感激。

UI

<div>
<table class="students">
      <thead>
          <tr>
              <th>Name</th>
          </tr>
      </thead>
      <tbody>
          <tr>
              <td>
                    <span id ="nameSpan">elvis</span>
                </td>                             
          </tr>
      </tbody>
  </table>  
</div>

JS

$(document).ready(function(){
    var focusInName = '';
    var focusOutName = '';
    $(function () {
        $(document).on("click", ".span", function () {
            focusInName = $(this).html();
            var input = $('<input />', {
                'type': 'text',
                    'name': 'aname',
                    'value': $(this).html(),
                    'class': 'input'
            });

            $(this).parent().append(input);
            $(this).remove();
            input.focus();
            alert(focusInName);
        });

        $(document).on('blur', ".input", function () {
            focusOutName = $(this).val();
            var span = $(
                '<span />', {
                'class': 'span',
                    'html': $(this).val()
            });

            $(this).parent().append(span);
            $(this).remove();        
            alert(focusOutName);
        });
    });
});

小提琴:HERE

3 个答案:

答案 0 :(得分:2)

只需从范围中删除点

即可
 $(document).on("click", ".span", function () {

 $(document).on("click", "span", function () {

答案 1 :(得分:2)

由于您使用的是Class Selector (".class"),因此需要添加带有span元素的类span

<span class='span' id ="nameSpan">elvis</span>

DEMO

答案 2 :(得分:1)

删除。从第一个跨度:

(document).on("click", "span", function () {