如何引用Visualforce中指定的HTML元素ID并传递到JavaScript函数?
-
10-10-2019 - |
题
我有生成输入文本字段的APEX标签。
<apex:page id="my_page">
<apex:inputText id="foo" id="c_txt"></apex:inputText>
</apex:page>
当有人单击此字段时,我想执行JavaScript。
但是,当我检查HTML源时,将变成输入标签的APEX标签(我认为)动态生成的部分。
<input type="text" size="50" value="Tue Nov 16 00:00:00 GMT 2010"
name="j_id0:j_id3:j_id4:c_txt" id="j_id0:j_id3:j_id4:c_txt">
如您所见,ID具有垃圾部分:(
id="j_id0:j_id3:j_id4:c_txt"
在我的JavaScript中,我想 getElementById('c_txt')
但这当然不起作用。如何处理这个???
更新
好像我可以做到这一点,但不起作用...
<apex:includeScript value="{!URLFOR($Resource.datepickerjs)}"></apex:includeScript>
<apex:inputText id="foo" id="c_txt" onclick="javascript:displayDatePicker()" />
datepickerjs
var elem = getElementById('c_txt');
alert(elem);
警报显示“ null”,因此一定有问题。
即使此警报也返回null ...
var targetDateField = document.getElementById('{!$Component.my_page:c_txt}');
alert(targetDateField);
解决方案 2
我解决了问题。
$ compoent全局visualforce表达式只能在我的搜索中不在JavaScript内部的Visualforce代码中使用。
下面的代码正常工作。现在,它可以将InputText字段中的值输出到JS警报消息,现在您可以将ID属性传递给JavaScript并处理任何需要的任务。
Created Date: <apex:inputText id="dah" value="{!created}" size="50"
onclick="javascript:go('{!$Component.dah}')"></apex:inputText>
<script>
function go(field) {
var huh = document.getElementById(field).value;
alert(huh); //returns the string u put inside of input text field
}
</script>
其他提示
您可以使用 $Component
JavaScript中的符号,您会这样使用:
var e = document.getElementById("{!$Component.ComponentId}");
但是,要警惕的一件事是,如果您的元素包含在具有ID的几个级别的Visualforce标签中:
<apex:pageBlock id="theBlock">
<apex:pageBlockSection id="theBlockSection">
<apex:commandLink action="{!someAction}" value="LINK!" id="theLink"/>
// snip
// in javascript you would reference this component using:
document.getElementById("{!$Component.theBlock.theSection.theLink}");
不隶属于 StackOverflow