How do I access a DIV from javascript, if ASP.NET mangles its ID?

六月ゝ 毕业季﹏ 提交于 2019-12-07 15:42:41

问题


I have a web page that contains a "div" element. On the page, there is javascript to reference the div: document.getElementById('divId'). This was working fine until another developer redesigned the page to use an ASP master page.

Now, document.getElementById('divId') returns null. It appears that ASP.net prepends some characters to the names of elements within contents forms when you use a master page. How can I know what the id of the div is when the page loads?

Update Allow me to give a specific example to clarify the question: My page had a div with ID divNotice. After changing my page to use a master page, I see when I print the source to the page that renders that the div ID is ctl00_ContentPlaceHolder1_divNotice. My question is, how am I supposed to know what the div ID is going to be when the framework is done with it?


回答1:


I think that this is what you looking for.

document.getElementById('<%=divNotice.ClientID%>')

to get the ID of your element as appears on the html page use .ClientID

Hope this help.




回答2:


Dynamically create the javascript using Control.ClientID to determine the calculated ID of div.

document.getElementById('<%= DivControl.ClientID %>')

Or search for the element on the client side using the base ID as a search pattern. See here: A generic way to find ASP.NET ClientIDs with jQuery

I prefer the server side calculation, but if you don't do it often and/or your current design prohibits it, the client side way is a reasonable workaround.




回答3:


you can check i the element exists by checking if it returns not null

if (document.getElementById('divId') != null) { /* do your stuff*/ }

in other words:

if (document.getElementById('divId')) { /* do your stuff*/ }

now you have edited you orginal question i got it.. i would do something like this:

var arrDivs = document.getElementsByTagName('div'),
    strDivName = "divId";

for (i=0;i<=arrDivs.length;i++){
    if( arrDivs[i].id.indexOf(strDivName) != -1) {
        alert("this is it")
    }
}

you can see a demo here: http://jsfiddle.net/pnHSw/2/

i think you could do it better with a regex.

But this is a pure JS way i don't know ASP.net

edit: i think Aristos solution is much cleaner :P




回答4:


maybe you can use a descendent selector un css

<div id="wrapperControler">
    <controler id="controler"></controler>
</div>

wrapperControler controler{

 dosomething;

}



来源:https://stackoverflow.com/questions/3048201/how-do-i-access-a-div-from-javascript-if-asp-net-mangles-its-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!