I want开发者_开发知识库 to retireve the selection and check the node of the selection. I'm trying following code. But I think, I'm not able to point to the selection and so the code fails.
<head>
<script type="text/javascript">
function SelectAnchorNode () {
if (window.getSelection) { // Firefox, Opera, Google Chrome and Safari
var selection = window.getSelection ();
if (selection.anchorNode) {
var rangeToSelect = document.createRange ();
alert(selection.anchorNode.nodeName);
} else {
alert ("Your browser does not support this example!");
}
}
</script>
</head>
<body>
<button onclick="SelectAnchorNode ();">Click to check!</button>
<br /><br />
<div>
<div>This is the first line.</div>
<p>This is the second line.</p>
</div>
</body>
You have some errors in your code, your missing a "}" to close the function.
Also this wont return true since the selection is made on a button and not on an anchor (link)
Try this code (I understand if this isn't what you want, but it makes your example work)
<html>
<head>
<script type="text/javascript">
function SelectAnchorNode () {
if (window.getSelection) { // Firefox, Opera, Google Chrome and Safari
var selection = window.getSelection();
if (selection.anchorNode) {
var rangeToSelect = document.createRange();
alert(selection.anchorNode.nodeName);
} else {
alert ("Your browser does not support this example!");
}
}
}
</script>
</head>
<body>
<a onclick="SelectAnchorNode();">Click to check!</a>
<br /><br />
<div>
<div>This is the first line.</div>
<p>This is the second line.</p>
</div>
As you can see I replaced "button" with "a", and added a missing "}"
EDIT!
Try this line instead, (I have now assumed that you want to get the selection made by the user, and that you don't want to create a selection with javascript?)
alert(selection.anchorNode.parentNode.nodeName);
Depending on where you start your selection you will get different results, you also need to first check if there was a text node selected or not (since I could make a selection directly in body). But I hope this brings you closer to your solution.
Regards
Tobias
精彩评论