如何引用visualforce中指定的html元素id并传递给javascript函数?

mas*_*san 9 javascript salesforce visualforce apex-code

我有一个生成输入文本字段的顶点标记.

<apex:page id="my_page">
    <apex:inputText id="foo" id="c_txt"></apex:inputText>
</apex:page>
Run Code Online (Sandbox Code Playgroud)

当有人点击此字段时,我想执行javascript.

但是当我检查HTML源代码时,这个成为输入标签的顶点标签有(我认为)动态生成的部分.

   <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">
Run Code Online (Sandbox Code Playgroud)

正如你可以看到id有垃圾部分:(

id="j_id0:j_id3:j_id4:c_txt"
Run Code Online (Sandbox Code Playgroud)

在我的Javascript中,我正在努力,getElementById('c_txt')但这当然不起作用.怎么处理这个?

UPDATE

好像我可以做到这一点,但没有工作......

<apex:includeScript value="{!URLFOR($Resource.datepickerjs)}"></apex:includeScript>

<apex:inputText id="foo" id="c_txt" onclick="javascript:displayDatePicker()" />
Run Code Online (Sandbox Code Playgroud)

datepickerjs

var elem = getElementById('c_txt');
alert(elem);
Run Code Online (Sandbox Code Playgroud)

警报显示'null',因此必定是错误的.

即使这个警报返回null ...

var targetDateField = document.getElementById('{!$Component.my_page:c_txt}');
alert(targetDateField);
Run Code Online (Sandbox Code Playgroud)

Mat*_*cey 6

您可以$Component在javascript中使用表示法,您可以这样使用它:

var e = document.getElementById("{!$Component.ComponentId}");
Run Code Online (Sandbox Code Playgroud)

但要注意的一件事是,如果您的元素包含在具有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}");
Run Code Online (Sandbox Code Playgroud)

  • 奇怪的是,如果使用$ Component.block.section的<script>在块之外的任何地方都不起作用并返回空. (4认同)

mas*_*san 5

我解决了我的问题.

$ 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>
Run Code Online (Sandbox Code Playgroud)