Come posso evidenziare le parole in un testo con jQuery?

Come posso evidenziare le parole in un testo con jQuery?

Evidenziare le parole in un testo è un'operazione resa più semplice da jQuery. Tuttavia occorre ricordare che la definizione di parola non coincide con il suo significato grammaticale nell'esempio che mostreremo.

Possiamo creare il seguente plugin:


(function( $ ) {

$.fn.chunkify = function( options ) {

		$.fn.chunkify.settings = {
        	separator: /\s/,
        	wrapper: "span",
        	klass: "chunk"
        };
        
        options = $.extend( $.fn.chunkify.settings, options );

		return this.each(function() {
			
			var $element = $( this );
		    var num = 0;
		    var text = $element.text();
		    
		    
		    var parts = text.split( options.separator );
		    var html = "";
		    
		    for( var i = 0; i < parts.length; ++i ) {
		    
		        num++;
		        
		        var part = parts[i];
		        
		        html += "<" + options.wrapper + " class='" + options.klass + num + "'>" + part + "</" + options.wrapper + "> ";
		    
		    
		    }
		    
		    $element.html( html );
		
		}); 
	
	
   };
	
})( jQuery );

Demo e codice

jQuery: split text into elements

Torna su