ImageMapper Beatles demo won't run outside jsF

2019-07-16 13:11发布

问题:

This is really just a javascript question that is parenthetically related to the ImageMapper jQuery plugin.

I must re-ask this question which was closed due to poor question construction and unclear responses from OP. However, I am having identical problem and need assistance.

Like the previous OP, I am attempting to reproduce this jsfiddle: http://jsfiddle.net/nYkAG/396/, but the javascript won't run.

The OP links to her attempt to make it work and mine is identical. CtrlW to see the markup/javascript. Clearly we both missed something (probably due to a similar newbie factor). Could it be the onLoad() function referenced in the jsfiddle on the left-side panel?

I added a simple jQuery test, and it works:

$(function() {
    alert('Hi');
});

so I know the libraries are loading properly and there are no obvious errors in the code. However, I was unable to understand these lines and wonder if perhaps something is missing? However, they work in the jsFiddle..?

var inArea,
    map = $('#beatles'),
    captions = { //stuff here },
    single_opts = { //stuff here },
    all_opts = { //stuff here },
    initial_opts = { //stuff here };
opts = $.extend({}, all_opts, initial_opts, single_opts);

In any case, the example - as copy/pasted - does not work. What am I missing? Again, for complete javascript and markup, please see OP's original example.

回答1:

Put your code in a "ready" handler:

$(function() {
  // all of your current code here
});

The jsfiddle site does that for you, unless you tell it not to. See that selection pull-down on the left side, below where you choose your library, where it says "onLoad"? That means that jsfiddle wraps your JavaScript in a "load" handler for the window. What I'm suggesting is similar (the jsfiddle option "on DOM ready"). What you've got in your code is the equivalent of "No wrap - in <head>", and if you choose that setting and try your fiddle, it won't work.

What's going on here is that if your code runs before the HTML is parsed into the DOM, your search for "#beatles" will find nothing. By delaying things until the DOM is ready, you ensure that the code will find the element(s) it needs.