gpt4 book ai didi

javascript - 具有值 window.getSelection() 的 jquery 全局变量变为空

转载 作者:行者123 更新时间:2023-11-30 08:22:06 25 4
gpt4 key购买 nike

在一个函数中想要设置变量以便能够在其他函数中使用。变量的值为 window.getSelection()

我做了什么:

1) 在 div contenteditable 中选择了一些文本

2) 点击class="fa-link"。启动将 window.getSelection() 的值分配给变量 global_variable

的代码

3) 单击页面中的任何其他位置,例如 id="ahref_name"global_variable 的值变为空。

为什么 global_variable 变空了?我没有启动为 global_variable 赋值的代码。所以 global_variable 必须保持值...就像 some_test_var

在此处放置代码 https://jsfiddle.net/xpvt214o/565926/

代码如下:

HTML

<div contenteditable>To select something</div>

<button class="fa-link">fa-link</button>

<div id="contenteditable_menu_ahref" style="display:none" >
<input type="text" id="ahref_name" placeholder="Ahref name" />
</div>

jQuery

var global_variable = '';
var some_test_var = '';

$(document).on('click', '.fa-link', function(){

console.log ('fa-link clicked');

$("#contenteditable_menu_ahref").css("display", "block");

if (window.getSelection) {

global_variable = window.getSelection();
console.log( 'global_variable 01 ' + global_variable );

some_test_var = 'some test var';

$("#ahref_name").val(global_variable);

}

});



$(document).click(function() {
console.log( "global_variable 02 " + global_variable + ' / some_test_var ' + some_test_var );
});

最佳答案

试试这个:window.getSelection().getRangeAt(0).cloneContents();。问题是您正在接收一个对象,并且每次您选择 DOM 的不同部分时该对象都会更新。通过调用 getSelection().getRangeAt(0).cloneContents(),您将在变量中存储该选择的副本

关于javascript - 具有值 window.getSelection() 的 jquery 全局变量变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51730823/

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