如何知道 JSF 组件的 id 以便我可以在 Javascript 中使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6045307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:00:28  来源:igfitidea点击:

How can I know the id of a JSF component so I can use in Javascript

javascriptjsf

提问by ftravers

Problem:Sometimes you will want to access a component from javascript with getElementById, but id's are generated dynamically in JSF, so you need a method of getting an objects id. I answer below on how you can do this.

问题:有时您想使用 javascript 访问组件 getElementById,但 id 是在 JSF 中动态生成的,因此您需要一种获取对象 id 的方法。我在下面回答你如何做到这一点。



Original Question:I want to use some code like below. How can I reference the inputText JSF component in my Javascript?

原始问题:我想使用如下代码。如何在我的 Javascript 中引用 inputText JSF 组件?

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <head>
       <title>Input Name Page</title>
        <script type="javascript" >
          function myFunc() {
            // how can I get the contents of the inputText component below          
            alert("Your email address is: " + document.getElementById("emailAddress").value);
          }
       </script>
    </head>
    <h:body>
        <f:view>
            <h:form>
                Please enter your email address:<br/>
                <h:inputText id="emailAddresses" value="#{emailAddresses.emailAddressesStr}"/>
                <h:commandButton onclick="myFunc()" action="results" value="Next"/>
            </h:form>
        </f:view>
    </h:body>
</html>


Update: this post Client Identifiers in JSF2.0discusses using a technique like:

更新:这篇文章JSF2.0 中客户端标识符讨论了使用如下技术:

<script type="javascript" >
  function myFunc() {
    alert("Your email address is: " + document.getElementById("#{myInptTxtId.clientId}").value);
  }
</script>

<h:inputText id="myInptTxtId" value="backingBean.emailAddress"/>
<h:commandButton onclick="myFunc()" action="results" value="Next"/>

Suggesting that the attribute idon the inputTextcomponent creates an object that can be accessed with EL using #{myInptTxtId}, in the above example. The article goes on to state that JSF 2.0 adds the zero-argument getClientId()method to the UIComponentclass. Thereby allowing the #{myInptTxtId.clientId}construct suggested above to get the actual generated id of the component.

在上面的示例中,建议组件id上的属性inputText创建一个可以使用 EL 访问的对象#{myInptTxtId}。文章继续指出 JSF 2.0getClientId()UIComponent类添加了零参数方法。从而允许#{myInptTxtId.clientId}上面建议的构造获取组件的实际生成的 id。

Though in my tests this doesn't work. Can anyone else confirm/deny. The answers suggested below suffer from drawback that the above technique doesn't. So it would be good to know if the above technique actually works.

虽然在我的测试中这不起作用。其他任何人都可以确认/否认。下面建议的答案存在上述技术没有的缺点。所以最好知道上述技术是否真的有效。

采纳答案by ftravers

Answer:So this is the technique I'm happiest with. Doesn't require doing toomuch weird stuff to figure out the id of a component. Remember the whole point of this is so you can know the idof a component from anywhere on your page, not justfrom the actual component itself. This is key. I press a button, launch javascript function, and it should be able to access anyother component, not just the one that launched it.

回答:所以这是我最满意的技术。不需要做太多奇怪的事情来找出组件的 id。请记住,这样做的全部意义在于,您可以id从页面上的任何位置了解组件的名称,而不仅仅是从实际组件本身。这是关键。我按下一个按钮,启动 javascript 功能,它应该能够访问任何其他组件,而不仅仅是启动它的组件。

This solution doesn't require any 'right-click' and see what the id is. That type of solution is brittle, as the id is dynamically generated and if I change the page I'll have to go through that nonsense each time.

此解决方案不需要任何“右键单击”并查看 id 是什么。这种类型的解决方案很脆弱,因为 id 是动态生成的,如果我更改页面,我每次都必须经历这些废话。

  1. Bind the component to a backing bean.

  2. Reference the bound component wherever you want.

  1. 将组件绑定到支持 bean。

  2. 在任何地方引用绑定组件。

So here is a sample of how that can be done.

所以这里是如何做到这一点的示例。

Assumptions: I have an *.xhtml page (could be *.jsp) and I have defined a backing bean. I'm also using JSF 2.0.

假设:我有一个 *.xhtml 页面(可能是 *.jsp)并且我已经定义了一个支持 bean。我也在使用 JSF 2.0。

*.xhtml page

*.xhtml 页面

<script>
  function myFunc() {
    var inputText = document.getElementById("#{backBean.emailAddyInputText.clientId}")                 
    alert("The email address is: " + inputText.value );
  }
</script>

<h:inputText binding="#{backBean.emailAddyInputText}"/>
<h:commandButton onclick="myFunc()" action="results" value="Next"/>

BackBean.java

BackBean.java

UIInput emailAddyInputText;

Make sure to create your getter/setter for this property too.

确保也为这个属性创建你的 getter/setter。

回答by BalusC

You need to use exactly the ID as JSF has assigned in the generated HTML output. Rightclick the page in your webbrowser and choose View Source. That's exactly the HTML code which JS sees (you know, JS runs in webbrowser and intercepts on HTML DOM tree).

您需要完全使用 JSF 在生成的 HTML 输出中分配的 ID。右键单击网络浏览器中的页面并选择View Source。这正是 JS 看到的 HTML 代码(你知道,JS 在 webbrowser 中运行并拦截 HTML DOM 树)。

Given a

给定一个

<h:form>
    <h:inputText id="emailAddresses" ... />

It'll look something like this:

它看起来像这样:

<form id="j_id0">
    <input type="text" id="j_id0:emailAddress" ... />

Where j_id0is the generated ID of the generated HTML <form>element.

j_id0生成的 HTML<form>元素的生成 ID在哪里。

You'd rather give all JSF NamingContainercomponents a fixed idso that JSF don't autogenerate them. The <h:form>is one of them.

您宁愿给所有 JSFNamingContainer组件一个固定值,id这样 JSF 就不会自动生成它们。该<h:form>是其中之一。

<h:form id="formId">
    <h:inputText id="emailAddresses" value="#{emailAddresses.emailAddressesStr}"/>

This way the form won't get an autogenerated ID like j_id0and the input field will get a fixed ID of formId:emailAddress. You can then just reference it as such in JS.

这样,表单将不会像这样获得自动生成的 ID j_id0,而输入字段将获得固定的 ID formId:emailAddress。然后,您可以在 JS 中直接引用它。

var input = document.getElementById('formId:emailAddress');

From that point on you can continue using JS code as usual. E.g. getting value via input.value.

从那时起,您可以像往常一样继续使用 JS 代码。例如通过input.value.

See also:

也可以看看:



Updateas per your update: you misunderstood the blog article. The special #{component}reference refers to the currentcomponent where the EL expression is been evaluated and this works only inside any of the attributes of the component itself. Whatever you want can also be achieved as follows:

更新根据您的更新:你误解了这个博客的文章。特殊#{component}引用是指计算 EL 表达式的当前组件,这仅在组件本身的任何属性内起作用。任何你想要的也可以实现如下:

var input = document.getElementById('#{emailAddress.clientId}');

with (note the bindingto the view, you should absolutely notbind it to a bean)

with(注意binding视图,你绝对不应该将它绑定到 bean)

<h:inputText binding="#{emailAddress}" />

but that's plain ugly. Better use the following approach wherein you pass the generated HTML DOM element as JavaScript thisreference to the function

但这很丑陋。最好使用以下方法,将生成的 HTML DOM 元素作为 JavaScriptthis引用传递给函数

<h:inputText onclick="show(this)" />

with

function show(input) {
    alert(input.value);
}

If you're using jQuery, you can even go a step further by abstracting them using a style class as marker interface

如果您正在使用 jQuery,您甚至可以通过使用样式类作为标记接口将它们抽象化来更进一步

<h:inputText styleClass="someMarkerClass" />

with

$(document).on("click", ".someMarkerClass", function() {
    var $input = $(this);
    alert($input.val());
});

回答by Ivan Bochko

Id is dynamically generated, so you should define names for all parent elements to avoid j_id123-like ids.

Id 是动态生成的,因此您应该为所有父元素定义名称以避免类似 j_id123 的 id。

Note that if you use jQuery to select element - than you should use double slash before colon:

请注意,如果您使用 jQuery 来选择元素 - 则应该在冒号前使用双斜线:

    jQuery("my-form-id\:my-text-input-block\:my-input-id")

instead of:

代替:

    jQuery("my-form-id:my-text-input-block:my-input-id")

In case of Richfaces you can use el expression on jsf page:

对于 Richfaces,您可以在 jsf 页面上使用 el 表达式:

    #{rich:element('native-jsf-input-id')} 

to select javascript element, for example:

选择javascript元素,例如:

    #{rich:element('native-jsf-input-id')}.value = "Enter something here";

回答by planetjones

You can view the HTML source when this is generated and see what the id is set to, so you can use that in your JavaScript. As it's in a form it is probably prepending the form id to it.

您可以在生成时查看 HTML 源代码并查看 id 设置为什么,以便您可以在 JavaScript 中使用它。因为它是一个表单,所以它可能会在它前面加上表单 id。

回答by Christophe Roussy

I know this is not the JSF way but if you want to avoid the ID pain you can set a special CSS class for the selector. Just make sure to use a good name so that when someone reads the class name it is clear that it was used for this purpose.

我知道这不是 JSF 的方式,但是如果您想避免 ID 痛苦,您可以为选择器设置一个特殊的 CSS 类。只要确保使用一个好名字,这样当有人读到类名时就可以清楚地知道它是用于这个目的的。

<h:inputText id="emailAddresses" class="emailAddressesForSelector"...

In your JavaScript:

在你的 JavaScript 中:

jQuery('.emailAddressesForSelector');

Of course you would still have to manually manage class name uniqueness. I do think this is maintainable as long as you do not use this in reusable components. In that case you could generate the class names using a convention.

当然,您仍然需要手动管理类名的唯一性。我确实认为这是可维护的,只要您不在可重用组件中使用它。在这种情况下,您可以使用约定生成类名。

回答by Vinod Chauhan

<h:form  id="myform">
 <h:inputText  id="name" value="#{beanClass.name}" 
                a:placeholder="Enter Client Title"> </h:inputText>
</h:form>

This is a small example of jsf. Now I will write javascript code to get the value of the above jsf component:

这是jsf的一个小例子。现在我将编写javascript代码来获取上述jsf组件的值:

    var x = document.getElementById('myform:name').value; //here x will be of string type

   var y= parseInt(x,10); //here we converted x into Integer type and can do the 
                           //arithmetic operations as well