2014-10-27 67 views
-4

我想在javascript中添加一個自定義提醒框。我有一個JavaScript自定義警報框示例代碼,但它顯示一個靜態消息(這是在函數中給出),我想動態更改標題和消息。請告訴我在此#alert_button函數中添加標題和消息參數的位置。如何在JavaScript函數中添加參數?

/* 
    jQuery document ready 
    You can also drag custom box. 
*/ 
$(document).ready(function() { 
    $("#alert_button").click(function(e) { 
     e.preventDefault(); 
     /* 
      jAlert is function which will show custom alert. 
       It has two argument. 
      First argument is content for alert. 
       Second is the Alert heading . 
     */ 
     jAlert('title', 'message'); 
    }); 
}); 
+1

你想如何動態地改變信息? – Scimonster 2014-10-27 12:44:52

+0

從哪裏獲得'title'和'message'? – dfsq 2014-10-27 12:45:43

+0

通過傳遞兩個參數(標題,消息)alert_button函數 – 2014-10-27 12:46:00

回答

0

使用變量來實現這一點。

var prop_title = 'title', 
    prop_message = 'message', 
    condition = true; 

$("#alert_button").click(function (e) { 
    e.preventDefault(); 

    jAlert(prop_title, prop_message); 
}); 

if (condition) { 
    prop_message = 'Message is changed now'; 
} 

更改prop_title & prop_message respectivley會影響究竟會顯示,截至jAlert功能綁定在click事件發生是從這些變量屬性。

根據需要在代碼中更改condition或創建新消息來區分消息。

在這裏,您可以測試http://jsfiddle.net/60y4hmuc/

0

如果我理解正確你想JAlert標題和信息動態地設置。

如果僅通過單擊單個元素觸發JAlert($(「#alert_button」)作爲ID單個元素)),那麼我看不到任何動態分配值的問題。如果你的想法是對多個元素使用JAlert(比如$(「。alert_button」)(所以使用類並且有多個元素可以點擊)) - 你可以對這些元素使用額外的屬性,然後調用它們在JAlert變量 - 這樣的例子:

<button id="alert_button1" class="alert_button" title="Title in alert1" data-message="Message in alert1">alert button 1"</button> 

<button id="alert_button2" class="alert_button" title="Title in alert2" data-message="Message in alert2">alert button 2"</button> 

...

和在功能上只是寫的東西:

  • 獲取當前點擊的元素的標題廣告n個數據消息作爲變量
  • 觸發JAlert與這些變量
1

jQuery的可存儲data任何DOM元素,這樣你就可以存儲在您的按鈕titlesmessages,並訪問他們的「點擊」事件中(或任何其他)聽衆功能是這樣的:

$("#alert_button").data({title: 'some title', message: 'some message'}); 
$("#alert_button").click(function(e) 
{ 
    e.preventDefault(); 
    /* 
     jAlert is function which will show custom alert. 
     It has two argument. 
     First argument is content for alert. 
     Second is the Alert heading . 
    */ 

    jAlert($(e.target).data().title, $(e.target).data().message); 
}); 
+0

不知道'數據',謝謝!需要調查的是它在變化時被清除,變量保留在內存中,在某些情況下,更改DOM元素會重新創建它。無論如何+1 – 2014-10-27 16:48:51

相關問題