簡體   English   中英

使用jQuery選擇器更新元素

[英]Updating elements with jQuery selector

我遇到以下表單元素的情況:

<label for="edit-type-config-associated-element--2">Destination Data Element </label>
<input type="text" id="edit-type-config-associated-element--2"
   name="type_config[associated_element]" value="23" size="60" 
   maxlength="128" class="form-text ajax-processed" 
   style="visibility: hidden;">
<input type="text" id="edit-type-config-associated-element--2_display" 
   value="23" size="60" maxlength="128" 
   class="form-text ajax-processed dropdowntree_aux dropdowntree_input valid" 
   readonly="" style="top: 61.515625px; left: 15px; position: absolute; 
   width: 389px; height: 16px;">

我想將更改偵聽器添加到第二個輸入元素(由edit-type-config-associated-element--2_display標識),然后更改第一個輸入元素(由edit-type-config-associated-元素-2)。 這里要注意的是,每次顯示此表單時,兩個id末尾出現的數字都會加一(為什么他們不能使用一致的id,我不知道,但這就是我所堅持的)。

這是我用來嘗試完成此操作的JavaScript:

// Add a change listener to associated element link for dc mappings
$('.dropdowntree_input').live('change', function () {
    // Get the data element id
    var dataElementID = $.trim($(this).val()),
        dataElementLinks = Drupal.settings.data_element_links;
    console.log('text field has changed to: ' + dataElementID);
    if (dataElementLinks.hasOwnProperty(dataElementID)) {
        $('#linked_form_elements').show();
    } else {
        $('#linked_form_elements').hide();
    }
    // Update the underlying text input to contain the right value.
    $(':input[type="text"][name="type_config[associated_element]"]').val(dataElementID);

但是,這不起作用。 似乎在更新第二個文本字段時從未調用此函數。

有什么想法可以解決嗎?

謝謝。

看起來您在選擇器中缺少[

$('input[type="text"][name="type_config[associated_element]"]').val(dataElementID);
                     ^ here

另外,如果您使用的是jQuery> = 1.9,則不再支持.live()。

如果您使用的是jQuery> = 1.7,請改用.on(),而且由於第一和第二輸入是next / prev兄弟姐妹,因此您可以使用該關系來查找元素

$(document).on('change', '.dropdowntree_input', function () {
    var dataElementID = $.trim($(this).val()),
        dataElementLinks = Drupal.settings.data_element_links;
    console.log('text field has changed to: ' + dataElementID);
    if (dataElementLinks.hasOwnProperty(dataElementID)) {
        $('#linked_form_elements').show();
    } else {
        $('#linked_form_elements').hide();
    }
    //since the hidden element is the previous sibling
    $(this).prev().val(dataElementID);
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM