2012-07-30 107 views
1

我使用codemirror和jquery在瀏覽器中「模擬」一個xml編輯器。一些xml-Tags包含一個「on」屬性,其中包含兩個可能的值(true或false)。是否可以在onclick事件中切換這些值?是否可以使用codemirror/jquery插件?JS屬性值onclick替換

編輯:

自編碼的解決方案。

function attrtoggle(){ 
    var pos = editor.getCursor(); 
    var line = editor.getLine(pos.line); 
    var index = line.indexOf("on="); 

    if(index > 0){ 
     //define range 
     if (pos.ch -3 < index || pos.ch - 9 > index) 
      return false; 

     var len = 10; 
     var replace_pos = index + 4; 

     if(line.charAt(replace_pos) == "t"){ 
      //insert false 
      line = line.replace('true', 'false'); 
     } else{ 
      //insert true 
      line = line.replace('false', 'true'); 
     } 
     edited = pos.line; 
     editor.setLine(pos.line, line); 
    } 
} 

只需添加一個事件處理程序onclick事件

$(".CodeMirror").attr("onclick","javascript:attrtoggle()"); 
+0

只是爲了澄清:你在CodeMirror編輯XML和對XML喜歡'',你想,當用戶點擊文本編輯器節點上,有它改成''? – JoshMock 2012-07-30 17:39:15

+0

是的!哪種方式最好? – NaN 2012-07-30 20:25:46

回答

0

到目前爲止還不完善(糟糕的設計等),但它按預期工作:

只是觸發功能在onclick事件。

function attributeToggle(){ 

    var transitions = { 
     "on": { 
      "false":"true", 
      "true":"false" 
     } 
    } 


    var pos = editor.getCursor(); // object {line, ch} 
    var token = editor.getTokenAt(pos); 
    var line = editor.getLine(pos.line); 

    try{ 

     var prev_pos = token.start - 1; 
     var prev_token = editor.getTokenAt({'line':pos.line, 'ch':prev_pos}); 

     if(prev_token.className == "attribute") 
      var attr = prev_token.string; 
     else 
      return false; 

     if(typeof transitions[attr] === "undefined") //nothing to replace 
      return false; 

     var current_val = token.string.toLowerCase().replace(/(['"])/g, ""); 


     if(typeof transitions[attr][current_val] === "undefined") 
      return false; 

     var line_new = line.substring(0, token.start) + \ 
"\"" + transitions[attr][current_val] + "\"" + line.substring(token.end); 

     editor.setLine(pos.line, line_new); 


    } catch (e){ 
     console.log(e); 
    } 
}