Dynamic jQuery asp.net mvc messy code, how to refactor more cleanly
I'm building a very interactive site with lots of ajax type functions.
I'm starting to end up with a fair amount of message Jquery开发者_StackOverflow社区 code, all nestled in together with my bee sting tags.
For example
<% foreach (var group in Model.GroupBy(item => item.goalId))
{ %>
//$('#AddNew2<%= Html.Encode(group.Key) %>').html('<input type="text" name="" value=""/>');
$('#AddNew2<%= Html.Encode(group.Key) %>').one('click', function(event) {
$('#AddNew2<%= Html.Encode(group.Key) %>').html('<input id="AddNew2<%= Html.Encode(group.Key) %>" type="text" name="" value=""/>').focus();
$('#AddNew2<%= Html.Encode(group.Key) %>').bind('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
//Do something
alert("hello");
}
//This will display the keycode
//alert(code);
//
});
});
My Question is two fold
Rather than having all of this code inside a view, or the Master site template, can I refactor this else where, perhaps using a .ascx control? Or can I just import a .js file and still have <% %> tags work inside it?
Am I using jQuery in a very bad way? It feels that I am being too simplistic with my use of the selectors, as I feel there would be a much cleaner way to select the elements I need.
Please bare in mind that I will have many different lists of data that can all be added to/updated on the same page, potentially up to hundreds of different elements and id's.
First, you could (and arguably should) use a javascript variable to hold the value and simply re-use it. That will improve the readability of your code. Second, I'm not sure exactly what you are trying to do -- it looks like you are setting up a click handler on each element. I'd suggest that you give them all a class and then use the class as the selector for applying the element. Third, it appears that you are creating a new element with the same id as an existing element. That would be a no-no. You should give it a new id and/or name. You may not need the id on the exterior element if you use a class.
Ex.
Layout:
<% foreach (var group in Model.GroupBy(item => item.goalId)) { %>
<p>
<input type="button" value="Add" class="add-goal" />
<input type="hidden" value='<%= group.Key %>' />
</p>
<% } %>
Script
$('.add-goal').one( 'click', function() {
var goalid = $(this).next('input[type=hidden]').attr('value');
var parent = $(this).parent().html('');
$( '<input type="text" id="AddNew2' + goalid
+ '" name="AddNew2' + goalid + '" value="" />' )
.appendTo(parent)
.keypress( function(e) {
...
});
});
精彩评论