Prototype to jQuery conversion - Stuck
I've been struggling to convert some prototype code I have to jQuery, I've done some looking around google and found a few things but this last segment of code i'm struggling with.
Hopefully someone here could shed some light to what I'm doing wrong....
This is the prototype code that I'm trying to convert to jQuery:
<script type="text/javascript">
var catCounter = 0;
function addCategory(catId) {
var ce开发者_如何学运维ll;
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>
Thanks in advance for any help.
You never need to hide your 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);
}
If you want a more sleek approach: jsFiddle code
Plugin script file:
// 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);
Usage:
// 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());
});
});
精彩评论