Динамически добавить script через html +=
Есть такой код
<tbody> <?php $project_image_row = 0; ?> <?php foreach ($project_images as $project_image) { ?> <tr id="project_image-row<?php echo $project_image_row; ?>"> <td class="text-left"><a href="" id="thumb-image<?php echo $project_image_row; ?>" data-toggle="image" class="img-thumbnail"><img src="<?php echo $project_image['thumb']; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" /></a><input type="hidden" name="project_image[<?php echo $project_image_row; ?>][image]" value="<?php echo $project_image['image']; ?>" id="input-project_image<?php echo $project_image_row; ?>" /></td> <td><div class="form-group" id="product-to-project<?php echo $project_image_row; ?>" style="display:inherit"> <label class="col-lg-2 col-md-2 col-sm-2 col-xs-12 control-label"><?php echo $entry_product; ?></label> <div class="col-lg-10 col-md-10 col-sm-10 col-xs-12"> <input type="text" name="project_image[<?php echo $project_image_row; ?>][product_to_project]" value="" class="form-control" /> <div id="product-to-project-list<?php echo $project_image_row; ?>" class="well well-sm" style="height: 150px; overflow: auto; margin-bottom:0;"> <?php if(isset($project_image['products'])) { ?> <?php foreach($project_image['products'] as $product) { ?> <div id="product-to-project-list<?php echo $product['product_id']; ?>"><i class="fa fa-minus-circle"></i> <?php echo $product['name']; ?> <input type="hidden" name="project_image[<?php echo $project_image_row; ?>][product_to_project][]" value="<?php echo $product['product_id']; ?>" /> </div> <?php } ?> <?php } ?> </div> </div> </div></td> <td class="text-right"><input type="text" name="project_image[<?php echo $project_image_row; ?>][sort_order]" value="<?php echo $project_image['sort_order']; ?>" placeholder="<?php echo $entry_project_image_sort_order; ?>" class="form-control" /></td> <td class="text-left"><button type="button" onclick="$('#project_image-row<?php echo $project_image_row; ?>').remove();" data-toggle="tooltip" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td> </tr> <?php $project_image_row++; ?> <?php } ?> </tbody> у него есть динамиское добавление html кода var project_image_row = <?php echo $project_image_row; ?>; function addProjectImage() { html = '<tr id="project_image-row' + project_image_row + '">'; html += ' <td class="text-left"><a href="" id="thumb-image' + project_image_row + '"data-toggle="image" class="img-thumbnail"><img src="<?php echo $placeholder; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" /></a><input type="hidden" name="project_image[' + project_image_row + '][image]" value="" id="input-project_image' + project_image_row + '" /></td>'; html += '<td><div class="form-group" id="product-to-project' + project_image_row + '" style="display:inherit">'; html += ' <label class="col-lg-2 col-md-2 col-sm-2 col-xs-12 control-label"><?php echo $entry_product; ?></label>'; html += ' <div class="col-lg-10 col-md-10 col-sm-10 col-xs-12">'; html += ' <input type="text" name="project_image[' + project_image_row + '][product_to_project]" value="" class="form-control" />'; html += ' <div id="product-to-project-list' + project_image_row + '" class="well well-sm" style="height: 150px; overflow: auto; margin-bottom:0;">'; html += ' </div>'; html += ' </div>'; html += ' </div></td>'; html += ' <td class="text-right"><input type="text" name="project_image[' + project_image_row + '][sort_order]" value="" placeholder="<?php echo $entry_sort_order; ?>" class="form-control" /></td>'; html += ' <td class="text-left"><button type="button" onclick="$(\'#project_image-row' + project_image_row + '\').remove();" data-toggle="tooltip" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>'; html += '</tr>'; $('#project_images tbody').append(html); project_image_row++; } но также динамически надо добавлять этот скрипт $('input[name=\'project_image[<?php echo $project_image_row; ?>][product_to_project]\']').autocomplete({ 'source': function(request, response) { $.ajax({ url: 'index.php?route=catalog/product/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(request), dataType: 'json', success: function(json) { response($.map(json, function(item) { return { label: item['name'], value: item['product_id'] } })); } }); }, 'select': function(item) { $('input[name=\'project_image[<?php echo $project_image_row; ?>][product_to_project]\']').val(''); $('#product-to-project-list<?php echo $project_image_row; ?>' + item['value']).remove(); $('#product-to-project-list<?php echo $project_image_row; ?>').append('<div id="product-to-project-list<?php echo $project_image_row; ?>' + item['value'] + '"><i class="fa fa-minus-circle"></i> ' + item['label'] + '<input type="hidden" name="project_image[<?php echo $project_image_row; ?>][product_to_project][]" value="' + item['value'] + '" /></div>'); } }); $('#product-to-project-list<?php echo $project_image_row; ?>').delegate('.fa-minus-circle', 'click', function() { $(this).parent().remove(); }); Как сделать это? Тоже добавлять в 'html +=' если да то экранировать ли одинарные кавычки? Может как-то через each можно запускать скрипт? Может я и перемудрил. Но помогите кто чем сможет. |
Каков смысл $project_image_row?
|
Цитата:
|
Нумерация это одно, а вот идентификаторы объектов, это иное, и они должны быть уникальны. Исходя из этого, чтобы выполнить это $('input[name=\'project_image[<?php echo $project_image_row; ?>][product_to_project]\']').autocomplete({}), нужно порождать этот JS скрипт для каждой строки в цикле foreach.
Допустим (хотя этого и не видно в коде), но каким же образом будет обеспечиваться нумерация, а уж тем более уникальность идентификаторов при динамическом добавлении html = '<tr id="project_image-row' + project_image_row + '">';? |
Цитата:
<table id="project_images" class="table table-striped table-bordered table-hover"> <thead> <tr> <td class="text-left"><?php echo $entry_project_image; ?></td> <td class="text-right"><?php echo $entry_project_image_sort_order; ?></td> <td></td> </tr> </thead> <tbody> <?php $project_image_row = 0; ?> <?php foreach ($project_images as $project_image) { ?> <tr id="project_image-row<?php echo $project_image_row; ?>"> <td class="text-left"><a href="" id="thumb-image<?php echo $project_image_row; ?>" data-toggle="image" class="img-thumbnail"><img src="<?php echo $project_image['thumb']; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" /></a><input type="hidden" name="project_image[<?php echo $project_image_row; ?>][image]" value="<?php echo $project_image['image']; ?>" id="input-project_image<?php echo $project_image_row; ?>" /></td> <td><div class="form-group" id="product-to-project<?php echo $project_image_row; ?>" style="display:inherit"> <label class="col-lg-2 col-md-2 col-sm-2 col-xs-12 control-label"><?php echo $entry_product; ?></label> <div class="col-lg-10 col-md-10 col-sm-10 col-xs-12"> <input type="text" name="project_image[<?php echo $project_image_row; ?>][product_to_project]" value="" class="form-control" /> <div id="project-image-list<?php echo $project_image_row; ?>" class="well well-sm" style="height: 150px; overflow: auto; margin-bottom:0;"> <?php if(isset($project_image['products'])) { ?> <?php foreach($project_image['products'] as $product) { ?> <div id="product-to-project-list<?php echo $project_image_row; ?>_<?php echo $product['product_id']; ?>"><i class="fa fa-minus-circle"></i> <?php echo $product['name']; ?> <input type="hidden" name="project_image[<?php echo $project_image_row; ?>][product_to_project][]" value="<?php echo $product['product_id']; ?>" /> </div> <?php } ?> <?php } ?> </div> </div> </div></td> <td class="text-right"><input type="text" name="project_image[<?php echo $project_image_row; ?>][sort_order]" value="<?php echo $project_image['sort_order']; ?>" placeholder="<?php echo $entry_project_image_sort_order; ?>" class="form-control" /></td> <td class="text-left"><button type="button" onclick="$('#project_image-row<?php echo $project_image_row; ?>').remove();" data-toggle="tooltip" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td> </tr> <script type="text/javascript"> $('input[name=\'project_image[<?php echo $project_image_row; ?>][product_to_project]\']').autocomplete({ 'source': function(request, response) { $.ajax({ url: 'index.php?route=catalog/product/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(request), dataType: 'json', success: function(json) { response($.map(json, function(item) { return { label: item['name'], value: item['product_id'] } })); } }); }, 'select': function(item) { $('input[name=\'project_image[<?php echo $project_image_row; ?>][product_to_project]\']').val(''); $('#product-to-project-list<?php echo $project_image_row; ?>_' + item['value']).remove(); $('#project-image-list<?php echo $project_image_row; ?>').append('<div id="product-to-project-list<?php echo $project_image_row; ?>_' + item['value'] + '"><i class="fa fa-minus-circle"></i> ' + item['label'] + '<input type="hidden" name="project_image[<?php echo $project_image_row; ?>][product_to_project][]" value="' + item['value'] + '" /></div>'); } }); $('#project-image-list<?php echo $project_image_row; ?>').delegate('.fa-minus-circle', 'click', function() { $(this).parent().remove(); }); </script> <?php $project_image_row++; ?> <?php } ?> </tbody> <tfoot> <tr> <td colspan="2"></td> <td class="text-left"><button type="button" onclick="addProjectImage();" data-toggle="tooltip" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button></td> </tr> </tfoot> </table> А вот как добавить сюда скрипт? Я пытался добавлять через html += но такое ощещение что или я не правильно экранировал кавычки или он просто не будет работать? <script type="text/javascript"><!-- var project_image_row = <?php echo $project_image_row; ?>; function addProjectImage() { html = '<tr id="project_image-row' + project_image_row + '">'; html += ' <td class="text-left"><a href="" id="thumb-image' + project_image_row + '" data-toggle="image" class="img-thumbnail"><img src="<?php echo $placeholder; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" /></a><input type="hidden" name="project_image[' + project_image_row + '][image]" value="" id="input-project_image' + project_image_row + '" /></td>'; html += '<td><div class="form-group" id="product-to-project' + project_image_row + '" style="display:inherit">'; html += ' <label class="col-lg-2 col-md-2 col-sm-2 col-xs-12 control-label"><?php echo $entry_product; ?></label>'; html += ' <div class="col-lg-10 col-md-10 col-sm-10 col-xs-12">'; html += ' <input type="text" name="project_image[' + project_image_row + '][product_to_project]" value="" class="form-control" />'; html += ' <div id="product-to-project-list' + project_image_row + '" class="well well-sm" style="height: 150px; overflow: auto; margin-bottom:0;">'; html += ' </div>'; html += ' </div>'; html += ' </div></td>'; html += ' <td class="text-right"><input type="text" name="project_image[' + project_image_row + '][sort_order]" value="" placeholder="<?php echo $entry_sort_order; ?>" class="form-control" /></td>'; html += ' <td class="text-left"><button type="button" onclick="$(\'#project_image-row' + project_image_row + '\').remove();" data-toggle="tooltip" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>'; html += '</tr>'; $('#project_images tbody').append(html); project_image_row++; } //--></script> |
Цитата:
В вашем случае это не только бесполезная нумерация, но и "детская болезнь" порождающая ошибки на клиенте. Об уникальности ID на форуме уже столько переписано, что просто лень еще говорить об этом. А в JQ и современном JS возможностей обратиться к DOM элементам на странице помимо ID множество и селекторов хоть отбавляй. |
я понял что я сооружаю костыль но на ус друго не приходит.
Скажите такое будет работать если правильно экранировать кавычки <script type="text/javascript"><!-- var project_image_row = <?php echo $project_image_row; ?>; function addProjectImage() { html = '<tr id="project_image-row' + project_image_row + '">'; html += ' <td class="text-left"><a href="" id="thumb-image' + project_image_row + '" data-toggle="image" class="img-thumbnail"><img src="<?php echo $placeholder; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" /></a><input type="hidden" name="project_image[' + project_image_row + '][image]" value="" id="input-project_image' + project_image_row + '" /></td>'; html += '<td><div class="form-group" id="product-to-project' + project_image_row + '" style="display:inherit">'; html += ' <label class="col-lg-2 col-md-2 col-sm-2 col-xs-12 control-label"><?php echo $entry_product; ?></label>'; html += ' <div class="col-lg-10 col-md-10 col-sm-10 col-xs-12">'; html += ' <input type="text" name="project_image[' + project_image_row + '][product_to_project]" value="" class="form-control" />'; html += ' <div id="project-image-list' + project_image_row + '" class="well well-sm" style="height: 150px; overflow: auto; margin-bottom:0;">'; html += ' </div>'; html += ' </div>'; html += ' </div></td>'; html += ' <td class="text-right"><input type="text" name="project_image[' + project_image_row + '][sort_order]" value="" placeholder="<?php echo $entry_sort_order; ?>" class="form-control" /></td>'; html += ' <td class="text-left"><button type="button" onclick="$(\'#project_image-row' + project_image_row + '\').remove();" data-toggle="tooltip" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>'; html += '</tr>'; html += ' <script type="text/javascript">'; html += ' $(\'input[name=\'project_image[' + project_image_row + '][product_to_project]\']\').autocomplete({'; html += ' \'source\': function(request, response) {'; html += ' $.ajax({ url: \'index.php?route=catalog/product/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(request), dataType: 'json', success: function(json) { response($.map(json, function(item) { return { label: item['name'], value: item['product_id'] } })); } }); },'; html += ' 'select': function(item) {'; html += ' $('input[name=\'project_image[' + project_image_row + '][product_to_project]\']').val('');'; html += ' $('#product-to-project-list' + project_image_row + '_' + item['value']).remove();'; html += ' $('#project-image-list' + project_image_row + '').append('<div id='product-to-project-list' + project_image_row + '_' + item['value'] + ''><i class='fa fa-minus-circle'></i> ' + item['label'] + '<input type='hidden' name='project_image[' + project_image_row + '][product_to_project][]' value='' + item['value'] + '' /></div>');'; html += ' }'; html += ' });'; html += ' $('#project-image-list' + project_image_row + '').delegate('.fa-minus-circle', 'click', function() {'; html += ' $(this).parent().remove();'; html += ' });'; html += ' </script>'; $('#project_images tbody').append(html); project_image_row++; } |
Думайте заново, ибо это полнейшая чушь. Нельзя в цикле прописать множество одних и тех же функций. Если бы это сделать в РНР, то вы бы получили фатальную ошибку. JS этого не выдаст, но и работать так как вы предполагаете это не будет. Даже в случае если все будет грамотно и одна функция, все равно это работать не будет, так как функция будет порождать дубликаты ID, с которыми у вас клиент работает.
Читать это и думать. |
Цитата:
|
Может кому будет интересно. Вот решение моей задачи
это html <tbody> <?php $project_image_row = 0; ?> <?php foreach ($project_images as $project_image) { ?> <tr id="project_image-row<?php echo $project_image_row; ?>"> <input type="hidden" class="project_image_id" value="<?php echo $project_image_row; ?>" /> <td class="text-left"><a href="" id="thumb-image<?php echo $project_image_row; ?>" data-toggle="image" class="img-thumbnail"><img src="<?php echo $project_image['thumb']; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" /></a><input type="hidden" name="project_image[<?php echo $project_image_row; ?>][image]" value="<?php echo $project_image['image']; ?>" id="input-project_image<?php echo $project_image_row; ?>" /></td> <td class="project-products"> <div class="form-group" id="product-to-project<?php echo $project_image_row; ?>" style="display:inherit"> <label class="col-lg-2 col-md-2 col-sm-2 col-xs-12 control-label"><?php echo $entry_product; ?></label> <div class="col-lg-10 col-md-10 col-sm-10 col-xs-12 project-products-rows"> <input type="text" name="productsInput" value="" class="form-control" /> <div id="project-image-list<?php echo $project_image_row; ?>" class="well well-sm" style="height: 150px; overflow: auto; margin-bottom:0;"> <?php if(isset($project_image['products'])) { ?> <?php foreach($project_image['products'] as $product) { ?> <div id="product-to-project-list<?php echo $project_image_row; ?>_<?php echo $product['product_id']; ?>"><i class="fa fa-minus-circle"></i> <?php echo $product['name']; ?> <input type="hidden" name="project_image[<?php echo $project_image_row; ?>][product_to_project][]" value="<?php echo $product['product_id']; ?>" /> </div> <?php } ?> <?php } ?> </div> </div> </div> </td> <td class="text-right"><input type="text" name="project_image[<?php echo $project_image_row; ?>][sort_order]" value="<?php echo $project_image['sort_order']; ?>" placeholder="<?php echo $entry_project_image_sort_order; ?>" class="form-control" /></td> <td class="text-left"><button type="button" onclick="$('#project_image-row<?php echo $project_image_row; ?>').remove();" data-toggle="tooltip" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td> </tr> <?php $project_image_row++; ?> <?php } ?> </tbody> а это js var project_image_row = <?php echo $project_image_row; ?>; function addProjectImage() { html = '<tr id="project_image-row' + project_image_row + '">'; html += '<input type="hidden" class="project_image_id" value="<?php echo $project_image_row; ?>" />'; html += ' <td class="text-left"><a href="" id="thumb-image' + project_image_row + '" data-toggle="image" class="img-thumbnail"><img src="<?php echo $placeholder; ?>" alt="" title="" data-placeholder="<?php echo $placeholder; ?>" /></a><input type="hidden" name="project_image[' + project_image_row + '][image]" value="" id="input-project_image' + project_image_row + '" /></td>'; html += ' <td><div class="form-group" id="product-to-project' + project_image_row + '" style="display:inherit">'; html += ' <label class="col-lg-2 col-md-2 col-sm-2 col-xs-12 control-label"><?php echo $entry_product; ?></label>'; html += ' <div class="col-lg-10 col-md-10 col-sm-10 col-xs-12">'; html += ' <input type="text" name="productsInput" value="" class="form-control" />'; html += ' <div id="project-image-list' + project_image_row + '" class="well well-sm" style="height: 150px; overflow: auto; margin-bottom:0;">'; html += ' </div>'; html += ' </div>'; html += ' </div></td>'; html += ' <td class="text-right"><input type="text" name="project_image[' + project_image_row + '][sort_order]" value="" placeholder="<?php echo $entry_sort_order; ?>" class="form-control" /></td>'; html += ' <td class="text-left"><button type="button" onclick="$(\'#project_image-row' + project_image_row + '\').remove();" data-toggle="tooltip" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>'; html += '</tr>'; $('#project_images tbody').append(html); project_image_row++; initializeAutocomplete(); } var initializeAutocomplete = function () { var currentProductsInputObject; $('input[name=\'productsInput\']').keydown(function() { currentProductsInputObject = $(this); }); $('input[name=\'productsInput\']').click(function() { currentProductsInputObject = $(this); }); $("input[name=\'productsInput\']").autocomplete({ source: function(request, response) { $.ajax({ url: 'index.php?route=catalog/product/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(request), dataType: 'json', success: function(json) { response($.map(json, function(item) { return { label: item['name'], value: item['product_id'] } })); } }); }, select: function(item) { var project_image_id = currentProductsInputObject.parents('tr').find('.project_image_id').val(); $('input[name=\'project_image['+project_image_id+'][product_to_project]\']').val(''); $('#product-to-project-list'+project_image_id+'_' + item['value']).remove(); $('#project-image-list'+project_image_id+'').append('<div id="product-to-project-list'+project_image_id+'_' + item['value'] + '"><i class="fa fa-minus-circle"></i> ' + item['label'] + '<input type="hidden" name="project_image['+project_image_id+'][product_to_project][]" value="' + item['value'] + '" /></div>'); } }); var project_image_id = currentProductsInputObject.parents('tr').find('.project_image_id').val(); $('#project-image-list'+project_image_id+'').delegate('.fa-minus-circle', 'click', function() { $(this).parent().remove(); }); } initializeAutocomplete(); при динамическом добавлении строк в каждой из них срабатывает autocomplete :dance: |
Часовой пояс GMT +3, время: 00:32. |