无法通过javascript生成按钮

时间:2015-01-13 08:54:16

标签: javascript jquery

我正在尝试通过用户javascript功能在www.8ch.net / www.8chan.co上的评论框中添加格式选项。

这是一个可行的脚本:

/* load_js("http://example.com/script.js"); */

load_js("http://code.jquery.com/jquery-2.1.3.js")

/*<![CDATA[*/
function formatText(el,tagstart,tagend){
var selectedText=document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);// IE:Moz
var newText=tagstart+selectedText+tagend;
if(document.selection){//IE
document.selection.createRange().text=newText;
}
else{//Moz
el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
}
}
/*]]>*/

var formattingButtonsRow = "<tr><th>Formatting</th><td> Test </td></tr>";

$("table:first-of-type tbody:last tr:nth-child(3)").after(formattingButtonsRow);

这是一个没有的人:

/* load_js("http://example.com/script.js"); */

load_js("http://code.jquery.com/jquery-2.1.3.js")

/*<![CDATA[*/
function formatText(el,tagstart,tagend){
var selectedText=document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);// IE:Moz
var newText=tagstart+selectedText+tagend;
if(document.selection){//IE
document.selection.createRange().text=newText;
}
else{//Moz
el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
}
}
/*]]>*/

var formattingButtonsRow = "<tr><th>Formatting</th><td> <input type="button" value="Red Text" onclick="formatText(body,'==','==')"></input> </td></tr>";

$("table:first-of-type tbody:last tr:nth-child(3)").after(formattingButtonsRow);

我无法弄清楚为什么第二个没有生成按钮。

2 个答案:

答案 0 :(得分:0)

使用此:(转义)

    /* load_js("http://example.com/script.js"); */

load_js("http://code.jquery.com/jquery-2.1.3.js")

/*<![CDATA[*/
function formatText(el,tagstart,tagend){
    var selectedText=document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);// IE:Moz
    var newText=tagstart+selectedText+tagend;
    if(document.selection){//IE
        document.selection.createRange().text=newText;
    }
    else{//Moz
        el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
    }
}
/*]]>*/

var formattingButtonsRow = "<tr><th>Formatting</th><td> <input type=\"button\" value=\"Red Text\" onclick=\"formatText(body,'==','==')\"></input> </td></tr>";

$("table:first-of-type tbody:last tr:nth-child(3)").after(formattingButtonsRow);

答案 1 :(得分:0)

更改此行:

var formattingButtonsRow = "<tr><th>Formatting</th><td> <input type="button" value="Red Text" onclick="formatText(body,'==','==')"></input> </td></tr>";

到那一行:

var formattingButtonsRow = '<tr><th>Formatting</th><td> <input type="button" value="Red Text" onclick="formatText(body,\'==\',\'==\')"></input> </td></tr>';