2013-07-04 61 views
1

我使用HTML和Javascript製作了一個基本的XML格式化程序。我想添加一個刪除功能。基本上,我希望能夠刪除條目,但不清除或損壞任何其他數據。從大量數據的textarea中刪除某些文本

<contact 
<!--John Doe--> 
first_name="John" 
last_name="Doe" 
contact_type="sip" 
account_id="104" 
subscribe_to="sip:[email protected]" 
has_voicemail="1" 
can_monitor="1" 
> 
<numbers> 
<number dial="1064" dial_prefix="" label="Extension" /> 
<number dial="555-0123" dial_prefix="718" label="Work Line" primary="1" /> 

我在想的辦法是找到包含李四和<contact刪除到</numbers>

接觸標籤可以`的indexOf()中使用含有某些信息刪除該組。

對於上下文:我向plunkr添加了一個演示。這需要表單數據並將其導出到一個文本

http://run.plnkr.co/plunks/b9QKZ7KZP0IlcyeCTTc9/

+0

什麼*其他數據*不應該受到影響? – VisioN

+0

列表中的其他聯繫人。所以,如果我想刪除John Doe,而不是Jane。 –

+0

我沒有看到 ... – dandavis

回答

0

我想你可能嘗試其他方式。

  1. 創建一些Javascript對象來保存數據。
  2. 將對象呈現給該文本區域。
  3. 添加/刪除數據時,首先操作對象,然後重新顯示。

代碼看起來像

//Contact list. 
var contacts = []; 

// Contact class. 
function Contact() { 
    ... 
    this.name = ""; 
    this.numbers = [];// numbers 
    ... 
} 

Contact.prototype.toString = function(){ 
    return "<contact name=\"" + this.name + ...; 
}; 

// Add new Contact 
function addContact(params) { 

    var contact = new Contact(); 
    // set properties 
    // contact.name = name; 
    contacts.push(contact); 
    showContacts(); 
} 

// Add new Contact 
function deleteContact(name) { 

    for (var i = contacts.length-1; i >= 0; i--) { 
     if (contacts[i].name == name) { 
      contacts.splice(i, 1); 
      return; 
     } 
    } 
} 

// present contacts 
function showContacts(){ 
    var text = ""; 
    for(var c in contacts){ 
     text += c.toString(); 
    } 
    textarea.value = text; 
} 

// other functions like addNumber etc. 

代碼會變得有點複雜,但更清晰靈活。