gpt4 book ai didi

javascript - 单击按钮(包括内容)时如何将 div 替换为 textarea?

转载 作者:太空宇宙 更新时间:2023-11-04 15:12:18 25 4
gpt4 key购买 nike

我最近使用这个 Fiddle http://jsfiddle.net/GeJkU/

    function divClicked() {
var divHtml = $(this).html();
var editableText = $("<textarea />");
editableText.val(divHtml);
$(this).replaceWith(editableText);
editableText.focus();
// setup the blur event for this new textarea
editableText.blur(editableTextBlurred);
}

function editableTextBlurred() {
var html = $(this).val();
var viewableText = $("<div>");
viewableText.html(html);
$(this).replaceWith(viewableText);
// setup the click event for this new div
viewableText.click(divClicked);
}

$(document).ready(function () {
$("div").click(divClicked);
});

当我点击 div 时,它将用 textarea 替换 div 标签。我的问题是,当我使用上面的 javascript 单击按钮时,如何用 textarea 替换 div 标签?

有什么建议吗?

最佳答案

假设,我已经理解了你的问题,你可以试试下面的方法。

HTML:在每个 div 之后添加一个 button,如下所示。

<div>If no background color is set on the Element, or its background color is set to 'transparent', the default end value will be white.</div>
<button class='btn'>Edit</button>

jQuery: 修改代码如下。

function divClicked() {
var divHtml = $(this).prev('div').html(); //select's the contents of div immediately previous to the button
var editableText = $("<textarea />");
editableText.val(divHtml);
$(this).prev('div').replaceWith(editableText); //replaces the required div with textarea
editableText.focus();
// setup the blur event for this new textarea
editableText.blur(editableTextBlurred);
}

function editableTextBlurred() {
var html = $(this).val();
var viewableText = $("<div>");
viewableText.html(html);
$(this).replaceWith(viewableText);
// setup the click event for this new div
viewableText.click(divClicked);
}

$(document).ready(function () {
$(".btn").click(divClicked); //calls the function on button click
});

Working Demo

关于javascript - 单击按钮(包括内容)时如何将 div 替换为 textarea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18565816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com