简体   繁体   中英

Where do I put this JS code to make it work?

I essentially recreated the table section of what I needed to make JS for and put together some working code in JS fiddle, but when I try to add it to where the table section is or within any other functions that are called int he html it seems to break the page... any idea where to put this? http://jsfiddle.net/UyHj3/13/

$("tr.clickable.subheading td").click(function() {
    $(this).parents("tr.clickable.subheading").nextUntil("tr.clickable.subheading").toggle();
});​​

Your problem is that you're trying to attach an event handler to an element that doesn't exist in the DOM. in jsFiddle, by default the code runs after onload meaning the DOM + images are fully loaded.

Wrap the code in the DOM ready event:

$(function() {
    $("tr.clickable.subheading td").click(function() {
        $(this).parents("tr.clickable.subheading").nextUntil("tr.clickable.subheading").toggle();
    });
});

Updated Fiddle

or put the code in the end of the <body> tag, like with this Fiddle .
But the first option is considered to be a better practice.

ready event docs :

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

You always want to put event handlers inside a document.ready function, like

$(document).ready(function(){

//your code

});

Your updated fiddle: http://jsfiddle.net/ccross59/UyHj3/15/

Put in either

$(document).ready(function () {
   // I execute your code when the DOM is ready. 
});

Or

$(window).load(function () {
  // I execute your code when the entire page is loaded (including images or iframes)
});

Looks like you have some jQuery there, so make sure that you are including a reference to the jQuery library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

And put your code inside the $(document).ready(){}:

$(document).ready(function(){
// your code
};

There should be a JavaScript pane. Make sure you're using JQuery on the left hand menu.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM