2013-03-13 32 views
2

我想在不同的按鈕點擊時彈出不同的窗體。我爲此使用此代碼。但所有按鈕點擊顯示第一個內容表單。它如何解決? 代碼多個元素的Javascript

<a href="#" class="button">Click 1</a> 
<div id="modal"> 
    <div id="heading">Content form 1</div> 
</div> 
<a href="#" class="button">Click 2</a> 
<div id="modal"> 
    <div id="heading">Content form 2</div> 
</div> 
<!--jQuery--> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<script src="js/jquery.reveal.js"></script> 

<script type="text/javascript"> 
$(document).ready(function() { 
    $('.button').click(function (e) { // Button which will activate our modal 
    $('#modal').reveal({    // The item which will be opened with reveal 
     animation: 'fade',    // fade, fadeAndPop, none 
     animationspeed: 600,   // how fast animtions are 
     closeonbackgroundclick: true, // if you click background will modal close? 
     dismissmodalclass: 'close'  // the class of a button or element that will close an open modal 
    }); 
    return false; 
    }); 
}); 
</script> 
+2

ID必須是唯一的。你需要改變ID,也許你''(this).next('。modal')'而不是.. – Ohgodwhy 2013-03-13 04:42:13

+0

謝謝..它工作正常 – Aneesh 2013-03-13 04:45:46

回答

1

您正在使用非唯一的ID。它只會給你第一個。

<a href="#" class="button" data-modal="1">Click 1</a> 
<div id="modal"> 
    <div id="heading">Content form 1</div> 
</div> 
<a href="#" class="button" data-modal="2">Click 2</a> 
<div id="modal"> 
    <div id="heading">Content form 2</div> 
</div> 
<!--jQuery--> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<script src="js/jquery.reveal.js"></script> 

<script type="text/javascript"> 
$(document).ready(function() { 
    $('.button').click(function (e) { // Button which will activate our modal 
    $('#modal' + $(this).data('id')).reveal({    // The item which will be opened with reveal 
     animation: 'fade',    // fade, fadeAndPop, none 
     animationspeed: 600,   // how fast animtions are 
     closeonbackgroundclick: true, // if you click background will modal close? 
     dismissmodalclass: 'close'  // the class of a button or element that will close an open modal 
    }); 
    return false; 
    }); 
}); 
</script> 

觀察如何:

  1. 我加了你的每一個ID模式的背後的數字。
  2. 我如何在每個鏈接上添加一個名爲「data-id」的屬性,我們需要的對應號碼爲 。
  3. 我如何使用jQuery的美妙數據()方法來獲取相應的數字 。

該方法的優點是鏈接可以移動到他們需要的任何位置,而無需更改click事件的內部。阿卡我們不需要通過.next().parent().find()

0

正確的屬性來識別一組元素是class,不id時使用,這對於元素必須是唯一的。應用類名來代替編號,您的標記看起來像:

<div class="modal"> 
    ... 
</div> 

既然你試圖操縱該先點擊的按鈕的模式,最好的辦法是使用prev方法來選擇元素緊接的按鈕。

$('.button').click(function (e) { 
    $(this).prev('.modal').reveal({ 
     ... 
    }); 
    return false; 
});