问题描述:

I've a page in an ASP.net site where i've multiple content placeholders, script tags with JavaScript functions and others elements. I'm hiding all content holders and other html elements using JavaScript except a div which i want to display. But i get the other scripts running in that page. How can i remove them?

Any ideas?

Edit1

Lets consider i've a following page

<html>

<head>

<script type="text/javascript">

alert("unnecessary script")

</script>

</head>

<body>

<script type="text/javascript">

alert("another one")

</script>

<div id="div1">

Div 1</div>

<div id="div2">

Div 2</div>

<div id="div3">

Div 3</div>

<script type="text/javascript">

alert("one more")

</script>

</body>

</html>

I'm loading this page in an iFrame in another page where in the frame OnLoad() i call HideUnneededHTML() which hides everything except div2. How can i remove the unnecessary Javascript too before it gets loaded?

网友答案:

One thing you might try is to reassign the unnecessary function(s) to a new function that does nothing. Afterall, Javascript functions are first class objects so they can be assigned a new value. This will not remove the lines from your page, but it will render the functions useless. If you want to switch them off temporarily, assign their value to another variable and then reassign them. You can always switch them back to the value saved in the other variable.

<script type="text/javascript">
    function myAmazingFunction(){
       alert("Does Something");
    }
</script>

later...

<script type="text/javascript">
    myAmazingFunction = function(){};

    //Now, call it... 
    myAmazingFunction();
</script>

This is safe because it means that any other code that is calling these functions will not cause errors - they just wont do anything.

Give it a go and let me know how you get on.

Edit: I have confirmed that this approach should work. Here I switch the function from Does Something, to Does Something Else and back again.

<script type="text/javascript">
    function myAmazingFunction() {
        alert("Does Something");
    }
    myAmazingFunction();
    var temp = myAmazingFunction;
    myAmazingFunction = function() { alert("Does Something Else"); };
    myAmazingFunction();
    myAmazingFunction = temp;
    myAmazingFunction();
</script>

results in 3 alert boxes in this order:

Does Something
Does Something Else
Does Something
相关阅读:
Top