[英]How to access a Javascript variable from Table data in HTML?
我具有以下Javascript,並且想訪問HTML的td中已經具有ID的“ selection”變量
<script type="text/javascript">
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
if(selection.text) { return selection.text; }
return false;
}
return false;
}
$(document).ready(function() {
$('#content-area').mouseup(function() {
var selection = getSelected();
if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
alert('Sending the following text to the server via AJAX: ' + selection);
$.ajax({
type: 'post',
url: 'calculate.php',
data: 'selection=' + encodeURI(selection)
});
}
});
});
</script>
我要訪問“選擇”變量的位置是html的td,如下所示:
<td>
<input type="button" id="optionone" name="optionone" onclick="sendrequest(selection , <?php echo $r ?>);" value="Positive"/>
</td>
我嘗試使用id(content-area)但沒有幫助。 請幫忙。
您可以訪問類似的表格項。
var ptr = $("#tableid").find("#optionone"); // or .find("tr:first");
ptr.find("#optionone).remove(); // or ("tr:first").remove();
參考此評論:
斯圖:不,我想在td中訪問變量“選擇”的值,並將其傳遞給“ sendrequest” JS函數。 幫助– @ mario23
好的,因此您需要在onClick中選擇變量。 我對此有一個建議:
在您的dom中:
<input type="hidden" id="hidden_optionone" value='<?php echo $r ?>'>
您為什么不輸入以下內容作為點擊:
$("#optionone").click(function() {
var php_val = $("#hidden_optionone").val();
//$("body").data("get_selection") equals selection
sendrequest($("body").data("get_selection") , php_val);
});
最后
function getSelected() {
if(window.getSelection) { return window.getSelection(); }
else if(document.getSelection) { return document.getSelection(); }
else {
var selection = document.selection && document.selection.createRange();
// THIS IS WHAT IS NEEDED
$("body").data("get_selection",selection);
if(selection.text) { return selection.text; }
return false;
}
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.