IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Partie HTML dans une partie Javascript


Sujet :

JavaScript

  1. #1
    Membre éclairé
    Inscrit en
    Mai 2006
    Messages
    705
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 705
    Par défaut Partie HTML dans une partie Javascript
    Bonjour,

    J'ai ce bout de code (dans un fichier JS)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    b.push(
    					'<a ' +
    						'class="link depth-' + indent + '"' +
    						( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
    						( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
    					'>'+
     
    					for(i=0;i<MonTableau.length;i++){
    					  	+'<img class="ico" src="'+MonTableau[i]+'" width="40px" height="40px" />'+
    					}
     
    						/*'<span class="indent-' + indent + '"></span>' +*/
    						$this.text() +
    					'</a>'
    				);
    Le problème c'est que j'ai une erreur de compilation (au niveau de la concaténation) comme montre l'image suivante:

    Nom : error.png
Affichages : 175
Taille : 19,7 Ko

    C'est quoi le problème? merci en avance.

  2. #2
    Invité
    Invité(e)
    Par défaut
    Bonjour,

    Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    var addpictos = '';
    for(i=0;i<MonTableau.length;i++){
    	addicones += '<img class="ico" src="'+MonTableau[i]+'" width="40px" height="40px" />';
    }
     
    b.push(
    	'<a ' +
    	'class="link depth-' + indent + '"' +
    	( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
    	( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
    	'>'+
    	addicones +
    	$this.text() +
    	'</a>'
    );

  3. #3
    Expert confirmé
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 094
    Par défaut
    Version avec les méthodes DOM :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    'use strict';
     
    var $fragment = document.createDocumentFragment();
     
    for (var i = 0; i < MonTableau.length; i++) {
      var $img = document.createElement('img');
      $img.className = 'ico';
      $img.src = MonTableau[i];
      $img.width = 40;
      $img.height = 40;
      $fragment.appendChild($img);
    }
     
    var $a = document.createElement('a');
    $a.className = 'link depth-' + indent;
    if (typeof target !== 'undefined' && target) $a.target = target;
    if (typeof href   !== 'undefined' && href  ) $a.href   = href;
    $a.appendChild($fragment);
    $a.appendChild(document.createTextNode( $this.text() ));
    b.push($a);
     
    console.table(b);
    console.table(b.map(function ($a) { return $a.outerHTML; }));
    À exécuter avec la console F12 ouverte pour voir ce qui se passe.
    La FAQ JavaScript – Les cours JavaScript
    Touche F12 = la console → l’outil indispensable pour développer en JavaScript !

  4. #4
    Expert confirmé
    Avatar de sekaijin
    Homme Profil pro
    Urbaniste
    Inscrit en
    Juillet 2004
    Messages
    4 205
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 61
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Urbaniste
    Secteur : Santé

    Informations forums :
    Inscription : Juillet 2004
    Messages : 4 205
    Par défaut
    a le DOM mais pourquoi l'a-t-on inventé... ?


  5. #5
    Membre éclairé
    Inscrit en
    Mai 2006
    Messages
    705
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 705
    Par défaut
    Merci pour vos réponses, mais ça n'a pas marché.

    J'ai le code suivant

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    		b.push(
    					$i=$i+1;
    					alert($i);
    					'<a ' +
    						'class="link depth-' + indent + '"' +
    						( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
    						( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
    					'><img class="ico" src="./images/icons/symbol.png" width="40px" height="40px"/>' +
    						'<span class="indent-' + indent + '"></span>' +
    						$this.text() +
    					'</a>'
    				);
    Mais dans la méthode push (j'ai une erreur au niveau des 2 lignes en rouge) [Syntax error, insert ")" to complete Arguments]

    Voici le code de mon fichier JS:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    (function($) {
     
    	/**
    	 * Generate an indented list of links from a nav. Meant for use with panel().
    	 * @return {jQuery} jQuery object.
    	 */
     
    	var MonTableau = ["./images/icons/symbol.png", "./images/icons/interface.png","./images/icons/player.png","./images/icons/signs.png","./images/icons/video.png","./images/icons/telephone.png"];
     
     
    	$.fn.navList = function() {
     
    		var	$this = $(this);
    			$a = $this.find('a'),
    			b = [];
     
    		$a.each(function() {
     
    				var $i =0;
    			var	$this = $(this),
    				indent = Math.max(0, $this.parents('li').length - 1),
    				href = $this.attr('href'),
    				target = $this.attr('target');
     
    			/*b.push(
     
    				'<a ' +
    					'class="link depth-' + indent + '"' +
    					( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
    					( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
    				'><img class="ico" src="./images/icons/symbol.png" width="40px" height="40px" />' +
    					'<span class="indent-' + indent + '"></span>' +
    					$this.text() +
    				'</a>'
    			);*/
     
     
    			b.push(
    					$i=$i+1;
    					alert($i);
    					'<a ' +
    						'class="link depth-' + indent + '"' +
    						( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
    						( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
    					'><img class="ico" src="./images/icons/symbol.png" width="40px" height="40px"/>' +
    						'<span class="indent-' + indent + '"></span>' +
    						$this.text() +
    					'</a>'
    				);
     
    		});
     
    		return b.join('');
     
    	};
     
     
     
    	/**
    	 * Panel-ify an element.
    	 * @param {object} userConfig User config.
    	 * @return {jQuery} jQuery object.
    	 */
    	$.fn.panel = function(userConfig) {
     
    		// No elements?
    			if (this.length == 0)
    				return $this;
     
    		// Multiple elements?
    			if (this.length > 1) {
     
    				for (var i=0; i < this.length; i++)
    					$(this[i]).panel(userConfig);
     
    				return $this;
     
    			}
     
    		// Vars.
    			var	$this = $(this),
    				$body = $('body'),
    				$window = $(window),
    				id = $this.attr('id'),
    				config;
     
    		// Config.
    			config = $.extend({
     
    				// Delay.
    					delay: 0,
     
    				// Hide panel on link click.
    					hideOnClick: false,
     
    				// Hide panel on escape keypress.
    					hideOnEscape: false,
     
    				// Hide panel on swipe.
    					hideOnSwipe: false,
     
    				// Reset scroll position on hide.
    					resetScroll: false,
     
    				// Reset forms on hide.
    					resetForms: false,
     
    				// Side of viewport the panel will appear.
    					side: null,
     
    				// Target element for "class".
    					target: $this,
     
    				// Class to toggle.
    					visibleClass: 'visible'
     
    			}, userConfig);
     
    			// Expand "target" if it's not a jQuery object already.
    				if (typeof config.target != 'jQuery')
    					config.target = $(config.target);
     
    		// Panel.
     
    			// Methods.
    				$this._hide = function(event) {
     
    					// Already hidden? Bail.
    						if (!config.target.hasClass(config.visibleClass))
    							return;
     
    					// If an event was provided, cancel it.
    						if (event) {
     
    							event.preventDefault();
    							event.stopPropagation();
     
    						}
     
    					// Hide.
    						config.target.removeClass(config.visibleClass);
     
    					// Post-hide stuff.
    						window.setTimeout(function() {
     
    							// Reset scroll position.
    								if (config.resetScroll)
    									$this.scrollTop(0);
     
    							// Reset forms.
    								if (config.resetForms)
    									$this.find('form').each(function() {
    										this.reset();
    									});
     
    						}, config.delay);
     
    				};
     
    			// Vendor fixes.
    				$this
    					.css('-ms-overflow-style', '-ms-autohiding-scrollbar')
    					.css('-webkit-overflow-scrolling', 'touch');
     
    			// Hide on click.
    				if (config.hideOnClick) {
     
    					$this.find('a')
    						.css('-webkit-tap-highlight-color', 'rgba(0,0,0,0)');
     
    					$this
    						.on('click', 'a', function(event) {
     
    							var $a = $(this),
    								href = $a.attr('href'),
    								target = $a.attr('target');
     
    							if (!href || href == '#' || href == '' || href == '#' + id)
    								return;
     
    							// Cancel original event.
    								event.preventDefault();
    								event.stopPropagation();
     
    							// Hide panel.
    								$this._hide();
     
    							// Redirect to href.
    								window.setTimeout(function() {
     
    									if (target == '_blank')
    										window.open(href);
    									else
    										window.location.href = href;
     
    								}, config.delay + 10);
     
    						});
     
    				}
     
    			// Event: Touch stuff.
    				$this.on('touchstart', function(event) {
     
    					$this.touchPosX = event.originalEvent.touches[0].pageX;
    					$this.touchPosY = event.originalEvent.touches[0].pageY;
     
    				})
     
    				$this.on('touchmove', function(event) {
     
    					if ($this.touchPosX === null
    					||	$this.touchPosY === null)
    						return;
     
    					var	diffX = $this.touchPosX - event.originalEvent.touches[0].pageX,
    						diffY = $this.touchPosY - event.originalEvent.touches[0].pageY,
    						th = $this.outerHeight(),
    						ts = ($this.get(0).scrollHeight - $this.scrollTop());
     
    					// Hide on swipe?
    						if (config.hideOnSwipe) {
     
    							var result = false,
    								boundary = 20,
    								delta = 50;
     
    							switch (config.side) {
     
    								case 'left':
    									result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX > delta);
    									break;
     
    								case 'right':
    									result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX < (-1 * delta));
    									break;
     
    								case 'top':
    									result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY > delta);
    									break;
     
    								case 'bottom':
    									result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY < (-1 * delta));
    									break;
     
    								default:
    									break;
     
    							}
     
    							if (result) {
     
    								$this.touchPosX = null;
    								$this.touchPosY = null;
    								$this._hide();
     
    								return false;
     
    							}
     
    						}
     
    					// Prevent vertical scrolling past the top or bottom.
    						if (($this.scrollTop() < 0 && diffY < 0)
    						|| (ts > (th - 2) && ts < (th + 2) && diffY > 0)) {
     
    							event.preventDefault();
    							event.stopPropagation();
     
    						}
     
    				});
     
    			// Event: Prevent certain events inside the panel from bubbling.
    				$this.on('click touchend touchstart touchmove', function(event) {
    					event.stopPropagation();
    				});
     
    			// Event: Hide panel if a child anchor tag pointing to its ID is clicked.
    				$this.on('click', 'a[href="#' + id + '"]', function(event) {
     
    					event.preventDefault();
    					event.stopPropagation();
     
    					config.target.removeClass(config.visibleClass);
     
    				});
     
    		// Body.
     
    			// Event: Hide panel on body click/tap.
    				$body.on('click touchend', function(event) {
    					$this._hide(event);
    				});
     
    			// Event: Toggle.
    				$body.on('click', 'a[href="#' + id + '"]', function(event) {
     
    					event.preventDefault();
    					event.stopPropagation();
     
    					config.target.toggleClass(config.visibleClass);
     
    				});
     
    		// Window.
     
    			// Event: Hide on ESC.
    				if (config.hideOnEscape)
    					$window.on('keydown', function(event) {
     
    						if (event.keyCode == 27)
    							$this._hide(event);
     
    					});
     
    		return $this;
     
    	};
     
    	/**
    	 * Apply "placeholder" attribute polyfill to one or more forms.
    	 * @return {jQuery} jQuery object.
    	 */
    	$.fn.placeholder = function() {
     
    		// Browser natively supports placeholders? Bail.
    			if (typeof (document.createElement('input')).placeholder != 'undefined')
    				return $(this);
     
    		// No elements?
    			if (this.length == 0)
    				return $this;
     
    		// Multiple elements?
    			if (this.length > 1) {
     
    				for (var i=0; i < this.length; i++)
    					$(this[i]).placeholder();
     
    				return $this;
     
    			}
     
    		// Vars.
    			var $this = $(this);
     
    		// Text, TextArea.
    			$this.find('input[type=text],textarea')
    				.each(function() {
     
    					var i = $(this);
     
    					if (i.val() == ''
    					||  i.val() == i.attr('placeholder'))
    						i
    							.addClass('polyfill-placeholder')
    							.val(i.attr('placeholder'));
     
    				})
    				.on('blur', function() {
     
    					var i = $(this);
     
    					if (i.attr('name').match(/-polyfill-field$/))
    						return;
     
    					if (i.val() == '')
    						i
    							.addClass('polyfill-placeholder')
    							.val(i.attr('placeholder'));
     
    				})
    				.on('focus', function() {
     
    					var i = $(this);
     
    					if (i.attr('name').match(/-polyfill-field$/))
    						return;
     
    					if (i.val() == i.attr('placeholder'))
    						i
    							.removeClass('polyfill-placeholder')
    							.val('');
     
    				});
     
    		// Password.
    			$this.find('input[type=password]')
    				.each(function() {
     
    					var i = $(this);
    					var x = $(
    								$('<div>')
    									.append(i.clone())
    									.remove()
    									.html()
    									.replace(/type="password"/i, 'type="text"')
    									.replace(/type=password/i, 'type=text')
    					);
     
    					if (i.attr('id') != '')
    						x.attr('id', i.attr('id') + '-polyfill-field');
     
    					if (i.attr('name') != '')
    						x.attr('name', i.attr('name') + '-polyfill-field');
     
    					x.addClass('polyfill-placeholder')
    						.val(x.attr('placeholder')).insertAfter(i);
     
    					if (i.val() == '')
    						i.hide();
    					else
    						x.hide();
     
    					i
    						.on('blur', function(event) {
     
    							event.preventDefault();
     
    							var x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');
     
    							if (i.val() == '') {
     
    								i.hide();
    								x.show();
     
    							}
     
    						});
     
    					x
    						.on('focus', function(event) {
     
    							event.preventDefault();
     
    							var i = x.parent().find('input[name=' + x.attr('name').replace('-polyfill-field', '') + ']');
     
    							x.hide();
     
    							i
    								.show()
    								.focus();
     
    						})
    						.on('keypress', function(event) {
     
    							event.preventDefault();
    							x.val('');
     
    						});
     
    				});
     
    		// Events.
    			$this
    				.on('submit', function() {
     
    					$this.find('input[type=text],input[type=password],textarea')
    						.each(function(event) {
     
    							var i = $(this);
     
    							if (i.attr('name').match(/-polyfill-field$/))
    								i.attr('name', '');
     
    							if (i.val() == i.attr('placeholder')) {
     
    								i.removeClass('polyfill-placeholder');
    								i.val('');
     
    							}
     
    						});
     
    				})
    				.on('reset', function(event) {
     
    					event.preventDefault();
     
    					$this.find('select')
    						.val($('option:first').val());
     
    					$this.find('input,textarea')
    						.each(function() {
     
    							var i = $(this),
    								x;
     
    							i.removeClass('polyfill-placeholder');
     
    							switch (this.type) {
     
    								case 'submit':
    								case 'reset':
    									break;
     
    								case 'password':
    									i.val(i.attr('defaultValue'));
     
    									x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');
     
    									if (i.val() == '') {
    										i.hide();
    										x.show();
    									}
    									else {
    										i.show();
    										x.hide();
    									}
     
    									break;
     
    								case 'checkbox':
    								case 'radio':
    									i.attr('checked', i.attr('defaultValue'));
    									break;
     
    								case 'text':
    								case 'textarea':
    									i.val(i.attr('defaultValue'));
     
    									if (i.val() == '') {
    										i.addClass('polyfill-placeholder');
    										i.val(i.attr('placeholder'));
    									}
     
    									break;
     
    								default:
    									i.val(i.attr('defaultValue'));
    									break;
     
    							}
    						});
     
    				});
     
    		return $this;
     
    	};
     
    	/**
    	 * Moves elements to/from the first positions of their respective parents.
    	 * @param {jQuery} $elements Elements (or selector) to move.
    	 * @param {bool} condition If true, moves elements to the top. Otherwise, moves elements back to their original locations.
    	 */
    	$.prioritize = function($elements, condition) {
     
    		var key = '__prioritize';
     
    		// Expand $elements if it's not already a jQuery object.
    			if (typeof $elements != 'jQuery')
    				$elements = $($elements);
     
    		// Step through elements.
    			$elements.each(function() {
     
    				var	$e = $(this), $p,
    					$parent = $e.parent();
     
    				// No parent? Bail.
    					if ($parent.length == 0)
    						return;
     
    				// Not moved? Move it.
    					if (!$e.data(key)) {
     
    						// Condition is false? Bail.
    							if (!condition)
    								return;
     
    						// Get placeholder (which will serve as our point of reference for when this element needs to move back).
    							$p = $e.prev();
     
    							// Couldn't find anything? Means this element's already at the top, so bail.
    								if ($p.length == 0)
    									return;
     
    						// Move element to top of parent.
    							$e.prependTo($parent);
     
    						// Mark element as moved.
    							$e.data(key, $p);
     
    					}
     
    				// Moved already?
    					else {
     
    						// Condition is true? Bail.
    							if (condition)
    								return;
     
    						$p = $e.data(key);
     
    						// Move element back to its original location (using our placeholder).
    							$e.insertAfter($p);
     
    						// Unmark element as moved.
    							$e.removeData(key);
     
    					}
     
    			});
     
    	};
     
    })(jQuery);
    Que dois-je faire?

  6. #6
    Expert confirmé
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 094
    Par défaut
    Petite révision :

    lorsqu'on appelle une fonction, on lui passe en paramètre des expressions. Une expression c'est n'importe quel bout de code qui renvoie un résultat.
    une ligne (pour simplifier) qui se termine par un point-virgule est une instruction. Les instructions ne sont pas des expressions.

    Dans le cas présent, ça veut dire que tu ne peux pas enchaîner les instructions dans ton appel à .push. Pour expliquer ton message d'erreur, l'interpréteur voit ce passage comme une instruction :
    Il s'est arrêté au premier point-virgule, et il ne comprend pas car il manque une parenthèse fermante.

    Si tu nous disais plutôt ce que tu cherches à faire avec cette variable $i ?
    La FAQ JavaScript – Les cours JavaScript
    Touche F12 = la console → l’outil indispensable pour développer en JavaScript !

  7. #7
    Membre éclairé
    Inscrit en
    Mai 2006
    Messages
    705
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 705
    Par défaut
    Tout d'abord, Je vous remercie pour votre réponse pertinente.

    En fait, je veux utiliser la variable $i comme étant un compteur pour qu'elle s'incrémente avec chaque itération de la méthode $a.each() dans un premier lieu, puis inclure le code suivant:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    b.push(
    					
    					'<a ' +
    						'class="link depth-' + indent + '"' +
    						( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
    						( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
    					'><img class="ico" src='MonTableau[$i]' width="40px" height="40px"/>' +
    						'<span class="indent-' + indent + '"></span>' +
    						$this.text() +
    					'</a>'
    				);

  8. #8
    Expert confirmé
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 094
    Par défaut
    Et le code de jreaux62 ne marche pas ?
    La FAQ JavaScript – Les cours JavaScript
    Touche F12 = la console → l’outil indispensable pour développer en JavaScript !

  9. #9
    Membre éclairé
    Inscrit en
    Mai 2006
    Messages
    705
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 705
    Par défaut
    Voici ce que ça donne le code de jreaux62:

    Nom : error.png
Affichages : 116
Taille : 133,6 Ko

  10. #10
    Invité
    Invité(e)
    Par défaut
    Bonjour,
    pourquoi s'acharner à vouloir tout faire dans le b.push() ?

    il suffit de construire la chaine EN DEHORS du b.push() :

    Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    $i=$i+1;
    alert($i);
     
    var addchaine = '<a ' +
    	'class="link depth-' + indent + '"' +
    	( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
    	( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
    	'><img class="ico" src="./images/icons/symbol.png" width="40px" height="40px"/>' +
    	'<span class="indent-' + indent + '"></span>' +
    	$this.text() +
    	'</a>';
    // ici, tu fais ce que tu veux sur addchaine,.........
     
    // enfin :
    b.push( addchaine );

  11. #11
    Membre éclairé
    Inscrit en
    Mai 2006
    Messages
    705
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 705
    Par défaut
    Voici mon code modifié selon votre version:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    var MonTableau = ["./images/icons/symbol.png", "./images/icons/interface.png","./images/icons/player.png","./images/icons/signs.png","./images/icons/video.png","./images/icons/telephone.png"];
     
     
    	$.fn.navList = function() {
     
    		var	$this = $(this);
    			$a = $this.find('a'),
    			b = [];
     
    		$a.each(function() {
     
     
    			var	$this = $(this),
    				indent = Math.max(0, $this.parents('li').length - 1),
    				href = $this.attr('href'),
    				target = $this.attr('target');
    			var $i=0;
     
     
     
    			$i=$i+1;
    			var addchaine = '<a ' +
    			'class="link depth-' + indent + '"' +
    			( (typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
    			( (typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
    			'><img class="ico" src="'+MonTableau[$i]+'" width="40px" height="40px"/>' +
    			'<span class="indent-' + indent + '"></span>' +
    			$this.text() +
    			'</a>';
     
    			b.push(
     
    					addchaine
    				);
     
    		});
     
    		return b.join('');
     
    	};
    Voici le rendu:

    Nom : error.png
Affichages : 124
Taille : 152,6 Ko

  12. #12
    Expert confirmé
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 094
    Par défaut
    Tu n’as jamais exprimé clairement ton objectif, mais maintenant je crois comprendre : tu as une liste d’images dans MonTableau, et tu veux associer chacune de ces images à un lien différent de ta liste, c’est bien ça ?

    Pour obtenir l’index du lien dans .each(), pas besoin d’une variable locale. jQuery te passe l’index en paramètre. Exemple tiré de .each() :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    $( "li" ).each(function( index ) {
      console.log( index + ": " + $( this ).text() );
    });
    Adapté à ton code, ça donne :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    var MonTableau = [
      './images/icons/symbol.png',  './images/icons/interface.png',
      './images/icons/player.png',  './images/icons/signs.png',
      './images/icons/video.png',   './images/icons/telephone.png'
    ];
     
    $.fn.navList = function () {
      var b = [];
     
      $(this).find('a').each(function ( index ) {
        var $this = $(this),
          indent = Math.max(0, $this.parents('li').length - 1),
          href = $this.attr('href'),
          target = $this.attr('target');
     
        var addchaine = '<a class="link depth-' + indent + '"' +
          (target ? ' target="' + target + '"' : '') +
          (href ? ' href="' + href + '"' : '') +
          '><img class="ico" src="' + MonTableau[index] + '" width="40px" height="40px" />' +
          '<span class="indent-' + indent + '"></span>' +
          $this.text() + '</a>';
     
          b.push(addchaine);
      });
     
      return b.join('');
    };
    Tu n’as pas besoin de ces tests typeof … !== 'undefined' car tes variables href et target sont déclarées. Il suffit de les tester implicitement en tant que valeur booléenne (une chaîne vide équivaut à false).

    Ça reste optimisable, car tu ne tires pas parti des capacités de construction DOM de jQuery. Au lieu de ça, tu concatènes « à l’ancienne » du code HTML.


    Edit : dans le code que tu as posté on trouve cette documentation :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    /**
       * Generate an indented list of links from a nav. Meant for use with panel().
       * @return {jQuery} jQuery object.
       */
    Il est indiqué que la méthode navList renvoie un objet jQuery. Or, en réalité elle renvoie b.join('') qui correspond à du code HTML sous forme de string. Est-ce toi qui as fait cette modification ?

    Ça me dérange car j’étais en train de retravailler ton code pour qu’il retourne directement une collection jQuery. Mais si le reste de ton script a besoin d’une chaîne HTML, ça sera contre-productif.
    La FAQ JavaScript – Les cours JavaScript
    Touche F12 = la console → l’outil indispensable pour développer en JavaScript !

  13. #13
    Membre éclairé
    Inscrit en
    Mai 2006
    Messages
    705
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 705
    Par défaut
    Merci infiniment pour votre réponse, ça marche

    Il est indiqué que la méthode navList renvoie un objet jQuery. Or, en réalité elle renvoie b.join('') qui correspond à du code HTML sous forme de string. Est-ce toi qui as fait cette modification ?
    Non, ce n'est pas moi, en fait il s'agit d'une template à laquelle j'ai voulu ajouté des icônes.

  14. #14
    Expert confirmé
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 094
    Par défaut
    Ok.

    Pour info, voici ce que ça pourrait donner en utilisant les méthodes jQuery :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
      $.fn.navList = function () {
        this.find('li a').each(function ( index ) {
          var $this = $(this),
            indent = $this.parents('li').length - 1;
     
          $this
            .addClass('link depth-' + indent)
            .prepend($('<span>')
              .addClass('indent-' + indent)
            ).prepend($('<img>')
              .addClass('ico')
              .attr({
                width : 40,
                height: 40,
                src   : MonTableau[index]
              })
            );
        });
     
        return this;
      };
    La FAQ JavaScript – Les cours JavaScript
    Touche F12 = la console → l’outil indispensable pour développer en JavaScript !

Discussions similaires

  1. Intégrer une partie stockage dans une application ?
    Par nickylarson59 dans le forum Android
    Réponses: 6
    Dernier message: 30/05/2014, 10h59
  2. [AJAX] Extraction d'une partie HTML dans une requete Ajax
    Par Nabes dans le forum jQuery
    Réponses: 2
    Dernier message: 01/04/2013, 08h57
  3. Exploiter des données HTML dans une variable javascript
    Par beber005 dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 17/06/2011, 16h11
  4. Réponses: 23
    Dernier message: 28/09/2007, 13h16
  5. Afficher des balises HTML dans une chaine javascript
    Par lapaupiette dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 07/03/2007, 10h19

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo