我一直在努力将一些我必须转换成jQuery的原型代码,我在谷歌周围做了一些调查,发现了一些东西,但这是我正在挣扎的最后一部分代码。
希望这里的人能弄清楚我做错了什么.
--这是我试图转换为jQuery:的原型代码
<script type="text/javascript">
var catCounter = 0;
function addCategory(catId) {
var cell;
var row = $('showcategories').insertRow(0);
if (!catId) {
catId = $F('category');
}
row.id = 'showcategory'+catCounter;
cell = row.insertCell(0);
cell.innerHTML = $('catoption'+catId).text;
cell = row.insertCell(1);
cell.innerHTML = '<input type="hidden" name="categories[]" value="'+catId+'">';
cell.innerHTML += '<input type="button" value="Remove" onclick="removeCategory('+catCounter+'); return false;">'
catCounter++;
}
function removeCategory(catId) {
$('showcategories').deleteRow($('showcategory'+catId).rowIndex);
}
</script>,谢谢您的帮助.
发布于 2011-01-13 19:21:35
您不需要隐藏您的javascript:<!-- . //-->
function addCategory(catId) {
var cell;
var row = $('#showcategories').insertRow(0); //# used to idenitfy IDs
if (!catId) {
catId = $('#category'); //same here, just use an ID, not a form element name
}
row.id = 'showcategory'+catCounter;
cell = row.insertCell(0);
//it's faster to build a string than updating the DOM repeatedly
var output = = $('#catoption'+catId).text;
cell = row.insertCell(1);
output = '<input type="hidden" name="categories[]" value="'+catId+'">';
output += '<input type="button" value="Remove" onclick="removeCategory('+catCounter+'); return false;">'
cell.html(output)
catCounter++;
}
function removeCategory(catId) {
$('#showcategories').deleteRow($('#showcategory'+catId).rowIndex);
}发布于 2011-01-13 19:33:13
如果你想要一个更圆滑的方法:jsFiddle代码
插件脚本文件:
// Plugin Code (maybe name it jquery-addCategory.js and include it?)
;(function($){
var catCounter = 0;
$.fn.extend({
addCategory: function(catId){
if (!catId) var catId = $F('category'); // assume $F is a form element value?
// use return so we can continue chaining
return this.each(function(){
var rowId = 'showcategory'+catCounter;
// I assume catoption[N] is an element with that ID attribute
// thus my use of '#' prefix for jQuery
var cell1 = $('<td>').append($('#catoption'+catId).text());
var cell2 = $('<td>')
.append($('<input>').attr({
'type':'hidden',
'name':'categories[]',
'value':catId
})).append($('<input>').attr({
'type':'button',
'value':'Remove',
}).click(function(){
$(this).closest('tr').remove();
}));
// build the row from the cells above and append it
var row = $('<tr>').append(cell1).append(cell2);
$(this).append(row);
// increase your counter
catCounter++;
});
}
});
})(jQuery);用法:
// the code that goes in your document (#myTable is the table you're attaching the
// the new row on to)
$(function(){
$('#addRow').click(function(){
$('#myTable').addCategory($('#category').val());
});
});https://stackoverflow.com/questions/4684156
复制相似问题