2014-09-06 39 views
0

我想創建具有從輸入類型文本獲取的信息的DOM元素。更具體地說: 我希望用戶能夠寫出一個位置,並在他按下「Go!」後按鈕插入文本創建一個元素,我也想有一個刪除圖標,當按下刪除該插入。從input type ='text'創建元素JavaScript

我創建了我把輸入值的功能,但如果我創建另一個<img>內用同樣的方法,當我創建的第二個條目就會把另一<img>我不能創建的「Del」鍵

與前一個條目

search_btn.click(function() { 

    var place_reg = /^[a-z]+\d*[a-z]*(\s[a-z]+\d*[a-z]*)*?$/i; 
    var search_value = search_box.val(); 
    var final_result = search_value.trim(); 

    if (place_reg.test(final_result)) { 

     createDest(final_result);   

    } else { 

     alert('Please insert a valid destination'); 
    } 

    document.getElementById('search_box').value = ""; 
}); 

function toTitleCase(str) { 

    return str.replace(/\w\S*/g, function(txt){ return txt.charAt(0).toUpperCase() + 
txt.substr(1).toLowerCase();}); 
} 

function createDest(value) { 

    var destination_i_search = document.createElement("div"); 
    destination_i_search.innerHTML = toTitleCase(value); 
    destination_i_search.setAttribute("class" , "place");  
    $("#dest").append(destination_i_search);    

} 
+0

問題出在您未顯示的代碼中。請顯示其餘部分(例如,在JSFiddle中的HTML例子也會很好):) – 2014-09-06 06:51:40

+0

你有這個標籤的jQuery,但沒有使用jQuery。如果你這樣做,代碼會更短/更簡單,JQuery也是你的選擇嗎? – 2014-09-06 06:53:55

+0

是的,我也使用jquery,但我不是很習慣它。我無法在Jquery文檔中找到所需的 – 2014-09-06 07:04:40

回答

0

這是很難理解你希望是什麼做的,沒有一個完整的例子,但是從評論你可能想是這樣的:

的jsfiddle:http://jsfiddle.net/TrueBlueAussie/s6hn0n18/6/

我已經將其轉換爲在適當的情況下使用jQuery。

var search_btn = $('#search'); 
var search_box = $('#searchbox'); 

search_btn.click(function() { 
    var place_reg = /^[a-z]+\d*[a-z]*(\s[a-z]+\d*[a-z]*)*?$/i; 
    var search_value = search_box.val() || ""; 
    var final_result = search_value.trim(); 
    if (place_reg.test(final_result)) { 
     createDest(final_result); 
    } else { 
     alert('Please insert a valid destination'); 
    } 
    search_box.val(""); 
}); 

function toTitleCase(str) { 
    return str.replace(/\w\S*/g, function (txt) { 
     return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); 
    }); 
} 

function createDest(value) { 
    // use a div container 
    var div = $("<div/>"); 
    div.html(toTitleCase(value)); 
    div.addClass("place"); 
    // If you want to replace the previous entry 
    $("#dest").append(div); 
    var del = $('<input class="delete" type="button" value="X"/>'); 
    $("#dest").append(del); 
} 

// This is a delegated event handler, attached to a non-changing ancestor 
$(document).on('click', '.delete', function(){ 
    // Remove the previous div (if of class place) 
    $(this).prev('.place').remove(); 
    // Remove the delete button too 
    $(this).remove(); 
}); 

,關鍵是要增加一個委派的事件處理程序進行刪除按鈕。這些通過監聽指定的事件(在這種情況下爲click)冒泡到一個不變的祖先起作用。它應用jQuery選擇器。它調用導致事件的任何匹配元素的函數。如果沒有更接近變化的內容可用,則默認祖先是document。在這種情況下,您可以使用#dest

例如

$('#dest').on('click', '.delete', function(){ 
+0

是的,這是我想要的。當我回家時,我會提供完整的代碼 – 2014-09-06 07:52:34

相關問題