2011-12-12 100 views
0

例如我複製從api.jquery.comjQuery的.change()不觸發選擇 - 從api.jquery.com

$('.target').change(function() { 
    alert('Handler for .change() called.'); 
}); 

這個例子中我也嘗試:

$('#target').change(function() { 
    alert('Handler for .change() called.'); 
}); 

我複製它放到我的.js文件中,它包含在我的html中。我還有一個jQuery函數在那裏(開始$(窗口).load(函數(){...」

其他功能正在起作用。但上面的簡單的功能是沒有的。

的形式看起來像這樣的:

<form> 
    <select id="target" class="target"> 
     <option name="pp" value="6">6</option> 
     <option name="pp" value="12">12</option> 
    </select> 
</form> 

我只想用ID,但我添加的類只是用於測試但無論是作品

爲什麼沒有這個簡單的函數工作我需要做別的連接。?更改事件的功能?我是jQuery的新手,但我知道在javas中cript我必須讓表單的onchange事件調用函數才能發生。

編輯:好的,這裏是我包括的.js文件中的一切。正如你所看到的,只有一個其他功能。它干擾了嗎? 另外,我只在頁面上有一個表格,你在上面看到。我將會改變每頁顯示的結果數(6或12)。

$(window).load(function() { 
    $("img.gall_img").each(function() { // iterate through all img of class gall_img 
     var imgWidth = $(this).width(); // "$(this)" to access jQuery width() func 
     var divWidth = $(this).closest('div').width(); 
     //alert(imgWidth + " and " + divWidth); // for debugging 
     if(imgWidth > divWidth) { 
      var position = Math.round(-1 * ((imgWidth/2) - (divWidth/2))); // 
      position = position + "px"; // make position format "123px". 
       $(this).css("left", position); // "$(this)" to access jQuery css() func 
      } 
    }); 
}); 


$("#target").change(function() { 
    alert('Handler for .change() called.'); 
}); 
+0

處理程序綁定在DOMReady後面嗎? –

+0

你應該上傳完整的代碼 –

+0

你使用什麼瀏覽器版本? –

回答

2

認沽代碼裏面$(window).load功能,像這樣:

$(window).load(function() { 

//whatever code is already here 

$('.target').change(function() { 
    alert('Handler for .change() called.'); 
}); 

}); //end of $(window).load function 

$(window).load(function()告訴瀏覽器整個頁面加載包括圖像後,只運行該代碼。傳統上用jQuery你會看到$(document).ready(function() { ...它告訴瀏覽器在頁面加載之前不處理該代碼(不包括圖像)

如果你不需要等待圖像加載運行你的jQuery然後你可以用$(document).ready(function() {替換$(window).load(function() {

乾杯!

+0

謝謝,這工作。我還可以選擇添加一個單獨的$(document).ready,並將其餘的函數放在那裏?是否有可能在一個頁面上同時存在$和$(window).load?我需要爲我的圖像調整功能$(window).load(請參閱我編輯的問題)。 –

+0

你可以這樣做,因爲$(window).load等同於onLoad,而$(document).ready特定於jQuery - 但它通常不是必需的。如果您在處理代碼之前需要等待整個頁面(例如圖像)加載,通常只需使用$(window).load。對於99%的情況$(document).ready是完全正確的。 – themerlinproject

+0

我爲我的圖像函數保存了$(window).load,並創建了一個單獨的部分,其中包含$(document).ready,現在.change()工作。謝謝! –

0

我試過這個代碼的jsfiddle =>http://jsfiddle.net/GjScg/

而這種代碼應工作,有沒有被在更改事件所約束的任何其他JavaScript?也許還有其他一些代碼,導致錯誤?

0

你確定,它不工作? 這裏是一個有效鏈接的jsfiddle:http://jsfiddle.net/ayezutov/7pEP4/

UPDATE:

兩種版本:http://jsfiddle.net/ayezutov/7pEP4/1/

+1

「你確定,它不起作用嗎?」 - 很容易判斷一個警報窗口是否彈出。 jsfiddle將js自動包裝到$(document).ready類型的函數中,這就是它在jsfiddle中工作的原因。 – themerlinproject

+0

是的,你是對的。我的帖子後有足夠的答案,指出這一點,所以我沒有更新它;) –

1

嘗試把你的.change(..).ready(..)功能是這樣的:

$(document).ready(function() { 
    $('#target').change(function() { 
    alert('Handler for .change() called.'); 
    }); 
});