Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在button push-javascript上选择的div标记的内容_Javascript_Html_Select - Fatal编程技术网

在button push-javascript上选择的div标记的内容

在button push-javascript上选择的div标记的内容,javascript,html,select,Javascript,Html,Select,在得到一些帮助后,我对Javascript比较陌生,我得到了一个div标记的内容,当用户单击按钮时,我想选择它,但我无法让它工作。这似乎很简单,但我已经玩了几个小时,找不到解决办法 <div id="targetText">content content </div> <button type="button" onclick="selectBox()">Push to Select</button> 但是当我点击按钮时什么也没发生 当我要求它

在得到一些帮助后,我对Javascript比较陌生,我得到了一个div标记的内容,当用户单击按钮时,我想选择它,但我无法让它工作。这似乎很简单,但我已经玩了几个小时,找不到解决办法

<div id="targetText">content content </div>

<button type="button" onclick="selectBox()">Push to Select</button>
但是当我点击按钮时什么也没发生

当我要求它选择一个输入(如下所示)时,它可以正常工作,但是我想要选择的内容在一个div中

<input type="text" id="targetText" value="content content">

有什么建议吗?提前感谢

点击选择
<button type="button" onclick="selectBox(document.getElementById('targetText'))">Push to Select</button>

function selectBox(elem) {

//Create a range (a range is a like the selection but invisible)
var range = document.createRange();

// Select the entire contents of the element
range.selectNodeContents(elem);

// Don't select, just positioning caret:
// In front
// range.collapse();
// Behind:
// range.collapse(false);

// Get the selection object
var selection = window.getSelection();

// Remove any current selections
selection.removeAllRanges();

// Make the range you have just created the visible selection
selection.addRange(range);
功能选择框(elem){ //创建一个范围(范围与所选内容类似,但不可见) var range=document.createRange(); //选择元素的全部内容 范围。选择节点内容(元素); //不选择,只定位插入符号: //前面 //range.collapse(); //背后: //范围。塌陷(假); //获取选择对象 var selection=window.getSelection(); //删除所有当前选择 selection.removeAllRanges(); //使刚刚创建的范围成为可见选择 选择。添加范围(范围);

}

我推荐重复-
窗口中的第二个答案。getSelection()。选择所有子项(document.getElementById('targetText')
<button type="button" onclick="selectBox(document.getElementById('targetText'))">Push to Select</button>

function selectBox(elem) {

//Create a range (a range is a like the selection but invisible)
var range = document.createRange();

// Select the entire contents of the element
range.selectNodeContents(elem);

// Don't select, just positioning caret:
// In front
// range.collapse();
// Behind:
// range.collapse(false);

// Get the selection object
var selection = window.getSelection();

// Remove any current selections
selection.removeAllRanges();

// Make the range you have just created the visible selection
selection.addRange(range);