javascript - 在span标签上使用on函数

标签 javascript jquery html

我正在尝试使用 on 函数在跨度和输入文本字段之间切换,但我需要一些帮助来找出我做错了什么。

我为它创建了一个 fiddle here

用户界面

<div>
<span >My value here!</span>
</div>

JS

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

    $('document').on('blur',".input", function () {
        $(this).parent().append($('<span />').html($(this).val()));
        $(this).remove();
         focusOutName = $(this).val();
        alert(focusOutName);
    });
});

最佳答案

您应该将jquery的版本更改为1.9 并将类更改为 html 元素,如下所示:

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

输入字段也是如此:

$(document).on('blur',"input", function () {
//codes    
 }

编辑

如果您想将类设置为 html 元素,您可以执行以下操作:

var focusInName = '';
var focusOutName = '';
$(function () {
    $(document).on("click",".sp", function () {
        var input = $('<input class="box" />', {'type': 'text', 'name': 'aname','value': $(this).html()});
        $(this).parent().append(input);
        $(this).remove();
        input.focus();
        focusInName = $(this).html();
        alert(focusInName);
    });

    $(document).on('blur',".box", function () {
        $(this).parent().append($('<span class="sp" />').html($(this).val()));
        $(this).remove();
         focusOutName = $(this).val();
        alert(focusOutName);
    });
});

DEMO

关于javascript - 在span标签上使用on函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555126/

相关文章:

javascript - 在 Javascript 中退出函数之前强制加载页面

javascript - 当 Promise 被多次解析且协程具有下一个 yield 时,协程将如何表现

javascript - Angular <select> 标签多值传递

javascript - 使用 anchor 标记打开模式时页面重定向到空白链接

javascript - 单击按钮并打开子菜单后,如何使按钮保持在原位

javascript - 包含照片幻灯片的 iframe 在 Chrome 上中断

javascript - 使列表在按钮上不可拖动,单击 Sortable.js

jQuery:查找并替换所有属性

jquery - 从 bxSlider 中删除寻呼机

javascript - 检测到字符串时从类中获取 ID