我使用创建链接功能实现了富文本编辑器。我可以创建链接,但是当我想更新链接时,例如,我点击现有的锚节点并单击“链接”按钮,它不会显示原始网址。如何让它显示原始网址?到目前为止,这就是我所拥有的:
$.fn.createRichTextEditor = function(width, height = "auto") {
var iframeDocument;
var iframeDocumentId = this.attr("id") + "-rte-editor";
var newHtml = "<div id='rte-" + iframeDocumentId + "' class='rte'>" +
"<ul class='rte-toolbar'>" +
"<li id='createLink'><button id='rte-createLinkBtn-" + iframeDocumentId + "' class='rte-button-link' value='createLink' title='Link'>Create Link</button></li>" +
"</ul>" +
'<div id="' + iframeDocumentId + '-container"></div>' +
"</div>";
this.after(newHtml);
this.css('display', 'none');
var iframe = $('<iframe/>', {
id: iframeDocumentId,
class: 'rte-iframe',
style: 'width;100%;height:' + height,
load: function() {
iframeDocument = this.contentDocument;
iframeDocument.designMode = 'On';
$(this).find('body').html('<br><br/>');
this.contentWindow.focus(); //New
}
});
$('#' + iframeDocumentId + '-container').append(iframe);
};
$('.rte-button-link').click(function() {
var sText = iframeDocument.getSelection();
var anchorTag = sText.anchorNode.parentNode;
var url = $(anchorTag).prop('href');
if (!url) {
url = "https://";
}
var input = prompt("Please enter a url", url);
if (input !== null) {
iframeDocument.execCommand('insertHTML', false, '<a href="' + input + '" onclick="window.open(\'' + input + '\')" style="cursor: pointer;">' + sText + '</a>');
}
});
$("#editor").createRichTextEditor(500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="editor">
</div>
答案 0 :(得分:0)
您可以尝试anchorNode.parentNode
。这将返回HTML锚点节点,您可以像这样使用它。
var sText = iframeDocument.getSelection();
var anchorTag = sText.anchorNode.parentNode;
console.log($(anchorTag).prop('href'));