我如何将插入的URL添加到输入文本之后的图像中

how do I append the inserted URL into image after the inputed text?

本文关键字:输入 文本 之后 图像 URL 插入 添加      更新时间:2023-09-26

我已经写好了代码,但是jquery代码没有执行。

Enter URL :<input type="text">
<button id="btn"> continue
</button>
<div contenteditable="true"
id="bod">
Click on this text to start writting</div>
$(document).ready(function(){
$("btn").click(function(){
  $("bod").append($('input').html('<img alt="" src="'+$(this).val()+'">'))
    })
});

我还想用"input"或"textarea"来代替因为我想用ng-model(angularjs)标记那个字段

我相信这就是你想要完成的:

首先,您正在尝试使用没有#的id选择器引用您的元素。

$("bod")应为$("#bod"),依此类推。"#"表示ID。

而且你检索输入值的方式也是完全错误的。

如果您想要一个项目的值,请使用ID。否则,你将只使用通用元素选择器获得一个数组。我给你的输入一个id,所以你不只是试图获得$('input')

的值

(我在你的值中放了一个占位符图像地址,你可以删除它)

还可以全屏查看代码片段。小视图使它看起来像你的文本被删除,但它不是真的。只是当添加img时,所有内容的基线都低于代码片段查看器中的窗口。

$(document).ready(function(){
    $("#btn").click(function(){
        $("#bod").append('<img alt="" src="'+$('#inp').val()+'">');
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter URL :<input id="inp" type="text" value="http://placehold.it/300">
<button id="btn">continue</button>
<div contenteditable="true" id="bod">Click on this text to start writting</div>

如果我正确理解了你的要求,那么JQuery代码应该是这样的:

$(document).ready(function(){
    $("#btn").click(function(){
       var bodElem = $("#bod");
       var url = $("input").val();
       $('<img alt="" src="'+ url +'">').insertAfter(bodElem);
    });
});