[英]Replacing img src in textarea using jquery from a pop-up window
我正在嘗試使用彈出窗口中的jquery替換父窗口中的textarea和輸入框圖像源。 輸入框中的文本更改沒有任何問題,但是textarea框中的文本保持不變。
這是父窗口的代碼:
<textarea cols="100" rows="20" class="editor">
<a href="http://www.amazon.com">
<img src="image.jpg" alt="replace image source in this textbox" />
</a>
</textarea>
<input type="text" value="image.jpg" maxlength="255" MultiLine="false" Class="inputBox" style="width:875px;" />
<a href="/PopUpBox" class="popup">Click Here To Add An Image/s</a>
<script type = "text/javascript">
$('.popup').click(function (event) {
event.preventDefault();
window.open($(this).attr("href"), "popupWindow", "width=750, height=800, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes");
});
</script>
這是彈出窗口的代碼:
<div class="selectButton">
<input id="select" class="selectImage" type="button" data-imagepath="image2.jpg" value="Select">
</div>
<script type = "text/javascript">
$('.selectImage').live("click", function (e) {
var selectImage = $(this).data("imagepath");
window.opener.$(".editor img").attr("src", selectImage); // can't change img src in textarea box
window.opener.$(".inputBox").val(selectImage);
self.close();
e.preventDefault();
});
</script>
任何想法為什么這不起作用?
您無法在textarea中獲取圖像源。Textarea響應代碼而不是元素。
您可以使用div使其內容可編輯。
<div contenteditable="true"></div>
或獲取editor的值並將其粘貼到div中,然后從div中選擇圖片
var editor = $(".editor").val();
$(".output").html(editor);
jQuery live函數已棄用,請使用“ 0n”
嘗試用更新的HTML字符串替換textarea值,如下所示:
<script type = "text/javascript">
$('.selectImage').live("click", function (e) {
var selectImage = $(this).data("imagepath");
window.opener.$(".editor img").val(
'<a href="http://www.amazon.com">'
+ '<img src="'+selectImage+'" alt="replace image source in this textbox" />'
+'</a>');
window.opener.$(".inputBox").val(selectImage);
self.close();
e.preventDefault();
});
</script>
在彈出窗口中,只需替換以下JS代碼:
<script type = "text/javascript">
$('.selectImage').click(function (e) {
var selectImage = $(this).data("imagepath");
window.opener.$(".editor img").attr("src", selectImage); // can't change img src in textarea box
window.opener.$(".inputBox").val(selectImage);
self.close();
e.preventDefault();
});
</script>
@Vikram Deshmukh是正確的路線。 @Olalekan也是正確的,textarea的內容是文本,無法像HTML一樣進行操作。
我在這里發布了相同的問題以獲得答案:
這是可行的解決方案:
<script type = "text/javascript">
$('.selectImage').live("click", function (e) {
var selectImage = $(this).data("imagepath");
window.opener.$('.editor').val(function (i, value) {
return value.replace(/src="[^"]+"/, 'src="' + selectImage + '"');
});
window.opener.$(".inputBox").val(selectImage);
self.close();
e.preventDefault();
});
</script>
感謝你的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.