繁体   English   中英

如何从getSelection()jQuery获取锚href

[英]How to get the anchor href from getSelection() jquery

我使用创建链接功能实现了富文本编辑器。 我可以创建链接,但是当我想更新链接时,例如,我单击一个现有的锚节点,然后单击“链接”按钮,它不显示原始URL。 如何显示原始网址? 到目前为止,这就是我所拥有的:

 $.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> 

您可以尝试anchorNode.parentNode 这将返回HTML锚节点,您可以像这样使用它。

var sText = iframeDocument.getSelection();
var anchorTag = sText.anchorNode.parentNode;
console.log($(anchorTag).prop('href'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM