jQuery code still being executed even after being commented out

时光总嘲笑我的痴心妄想 提交于 2019-12-08 09:13:29

问题


I have a basic .js file with this inside it

//$('#show').html('<%= escape_javascript(render(:partial => 'show')) %>');

When the .js file is called, the code above gets executed and the partial is rendered even though it's commented out. When the code is deleted, the partial never gets rendered. The DOM remains unchanged, but I can see the partial being rendered by the server at the command line. What gives?


回答1:


You're commenting out the JavaScript--which executes on the client side.

The partial rendering happens on the server side, before the client ever sees the rendered JavaScript.

In other words, commenting out JavaScript has zero effect on the server-side processing. If you don't want the server-side string to be displayed, comment it out:

<%#= escape_javascript(etc) %>

Let's assume the partial renders like this:

<h1>Foo bar baz</h1>
<div>Plugh!</div>

Escaping this for JavaScript will turn the newline into a \n (and would escape single- and double-quotes, etc.) leaving you with this on the client side:

$('#show').html('<h1>Foo bar baz</h1>\n<div>Plugh!</div>');

Whether or not the JS is commented out or not, the partial is going to render unless you comment out the results of the escape_javascript Ruby code.

On the client side, if the JS is commented out, it shouldn't update show's HTML--are you saying it is?




回答2:


Check to see if this is the line or you have this call some place else:

//$('#show').html('<%=escape_javascript(render(:partial => 'show'))%>');alert('This is the line');



回答3:


Perhaps your escape_javascript function is inserting a newline? That would end the comment and cause anything after the newline to be executed.




回答4:


I had a similar issue and figured out a work around for what I wanted it for. Perhaps something like this will help you out!

Instead of commenting the lines of code out, try just building a logical operator that gives you an "on/off" toggle on the functions you want to run. I set mine up like this so I could turn off the script but keep it for future reference:

var toggle = 1; 

if(toggle == 2){
   functions that you want to run when turned on... 
}

Since your variable is not equal to two, the if statement will not render out what's stored inside of it, effectively 'commenting' that code out for you! To turn it back on all you have to do is change the 'toggle' variable back to 2 (or whatever 'on' value you want). Just a little work around I found for myself, hope that helps!



来源:https://stackoverflow.com/questions/10664025/jquery-code-still-being-executed-even-after-being-commented-out

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