我正在嘗試使用下拉列表的值作爲下一個函數的名稱。該字符串是正確的,並顯示在警報中。在代碼中明確寫入名稱也是可行的。但是在兩個函數的範圍內使用來自變量的部分根本不起作用。從函數傳遞給函數名的字符串變量不起作用
Drupal.behaviors.smart_inventory = {
attach: function(context, settings) {
// this should be in the scope of both functions
var selecttype;
$('#select-voc-content_types', context).change(function() {
contenttype = $(this).val();
secondary = $('#' + contenttype);
if($(secondary).length > 0)
{
// set the select list. tried an alert and the variable string is set
selecttype = '#select-voc-' + $(this).val();
$('.group-types').show();
$('#' + contenttype).show();
$('#object-ajax-form').hide();
}
else
{
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": contenttype }, frmDrupal);
}
});
// this does not respond as jquery does not accept the string as an element name
// or maybe the variable is not available here?
$(selecttype, context).change(function() {
var nodetype = $(this).val();
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": nodetype }, frmDrupal);
});
var frmDrupal = function(responseText) {
$('#object-ajax-form').show();
$('#object-ajax-form').html(responseText);
$('#object-node-form-message').hide();
}
}
};
如果發現這個工程!但是嵌套一個功能良好的做法?還是夠好? ;
Drupal.behaviors.smart_inventory = {
attach: function(context, settings) {
var selecttype;
$('#select-voc-content_types', context).change(function (selecttype) {
contenttype = $(this).val();
secondary = $('#' + contenttype);
if($(secondary).length > 0)
{
// set the select list
selecttype = '#select-voc-' + $(this).val();
$('.group-types').show();
$('#' + contenttype).show();
$('#object-ajax-form').hide();
}
else
{
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": contenttype }, frmDrupal);
}
$(selecttype , context).change(function() {
var nodetype = $(this).val();
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": nodetype }, frmDrupal);
});
});
@tvanfossen,使用[ID^= 「選擇-VOC-」]使DOM的掃描,並觸發到函數的調用。 – 2012-03-01 15:13:14
可能重複的http://stackoverflow.com/questions/4972303/how-do-i-get-ajax-contents-in-global-javascript-variable和其他許多 – 2012-03-01 15:13:43
要非常小心你不要開始雙註冊事件。 – DefyGravity 2012-03-01 16:39:13