单击时编辑HTML文本

时间:2015-03-25 09:15:50

标签: javascript html

我想通过点击来改变文字输入文字: 目前我已经:

<div class="wrapper">
    <span class="text-content">Double Click On Me!</span>
</div>

在javascript中:

//plugin to make any element text editable
$.fn.extend({
    editable: function () {
        $(this).each(function () {
            var $el = $(this),
            $edittextbox = $('<input type="text"></input>').css('min-width', $el.width()),
            submitChanges = function () {
                if ($edittextbox.val() !== '') {
                    $el.html($edittextbox.val());
                    $el.show();
                    $el.trigger('editsubmit', [$el.html()]);
                    $(document).unbind('click', submitChanges);
                    $edittextbox.detach();
                }
            },
            tempVal;
            $edittextbox.click(function (event) {
                event.stopPropagation();
            });

            $el.dblclick(function (e) {
                tempVal = $el.html();
                $edittextbox.val(tempVal).insertBefore(this)
                .bind('keypress', function (e) {
                    var code = (e.keyCode ? e.keyCode : e.which);
                    if (code == 13) {
                        submitChanges();
                    }
                }).select();
                $el.hide();
                $(document).click(submitChanges);
            });
        });
        return this;
    }
});

//implement plugin
$('.text-content').editable().on('editsubmit', function (event, val) {
    console.log('text changed to ' + val);
});

但我不知道如何更改双击简单点击!我试图用$ el.click()替换$ el.dblclick(...),但它不起作用。 有人有解决方案吗?

2 个答案:

答案 0 :(得分:1)

当您将$el.dblclick更改为$el.click时,它也会处理$(document).click(submitChanges);事件。因此$el.click处理程序应返回false以停止进一步的事件处理。

$el.click(function (e) { // <---------- click
  tempVal = $el.html();
  $edittextbox.val(tempVal).insertBefore(this).bind('keypress', function (e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {
      submitChanges();
    }
  }).select();
  $el.hide();
  $(document).click(submitChanges);
  return false; // <------------------------ stop further event handling
});

http://jsfiddle.net/zvm8a7cr/

答案 1 :(得分:0)

您可以使用html的contenteditable属性

var initialContent = $('.text-content').html();

$('.text-content')
.on('blur', function(){
  if(initialContent != $(this).html())
      alert($(this).text());
  if($(this).html() == ''){
    $(this).html(initialContent);
  }
})
.on('click', function(){
   if(initialContent == $(this).html()) {
     $(this).html('');
   }
});;
.text-content {
  border: 1px solid black;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="wrapper">
    <span contenteditable="true" class="text-content">Click On Me!</span>
</div>