简体   繁体   中英

Javascript global variable not retaining its value

I'm trying to access a global variable in two Javascript methods. The first one is supposed to write to the variable and the second one is supposed to read it.

I have the following code:

var selectedObj;
function first(){
    selectedObj = window.getSelection();
    alert(selectedObj);
}

function second(){
    alert(selectedObj);
}

So the user selects some text in an contenteditable textbox. When function first() runs, it does in fact display what was selected. So I know its value is going into the global variable selectedObj.

But before running function second(), the selected text becomes unselected. However, nothing happens that explicitly sets the value of selectedObj. Ergo, I would expect it to still retain the value of what was previously selected by the user.

But it doesn't. When the function second() runs, the alert is empty.

The alert won't be empty if the user doesn't deselect the text, so I know the global variable can work. But I need it to retain its value even if the user deselects the text.

How can I make this happen?

Like someone else suggested, setting it to a local variable (by value instead of reference) seems to work.

 var selectedObj; function first() { let newSelection = window.getSelection().toString(); selectedObj = newSelection; alert(selectedObj); } function second() { alert(selectedObj); } 
 Lorem ipsum yada yada <button onclick="first()">First</button> <button onclick="second()">Second</button> 

From the docs (man I love docs): Window.getSelection()

Returns a Selection object representing the range of text selected by the user or the current position of the caret.

You answered your own question really:

The alert won't be empty if the user doesn't deselect the text

You're assigning the result of window.getSelection() to your global.

selectedObj = window.getSelection();

When the result is empty, your global is empty. Like @larz said in his comment it's most likely in how/when funciton first is called.

as mentioned in question, before second() runs text becomes unselected causing selectedObj to set to empty value.

You should set the value of selectedObj if window.getSelection() !== ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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