Contexto: tengo una secuencia de comandos para una página de búsqueda que recupera el valor del filtro seleccionado de la URL y agrega el texto " en 'filtro'. " al encabezado h1 en la página de resultados de búsqueda.
Por ejemplo, si busca 'sql' y aplica el filtro 'Guía de instalación', la URL mostrará .../Search.htm?q=sql&f=Installation%20Guide y la página de resultados de búsqueda dirá: Your search for " sql" devolvió 9 resultados en la Guía de instalación.
Sin embargo, si no se selecciona ningún filtro, no hay ' f= ' y se agrega un espacio en blanco. En ese caso, la página de resultados de búsqueda dirá: Su búsqueda de "sql" arrojó 9 resultados en .
Aquí está el guión:
$(document).ready(function(){ var filter=(window.location.search.split('&').splice(1)) //Creates a "filter" variable whose value is the filter text. filter = decodeURI(filter) //Removes the codes used for spaces. filter = filter.substring(2) //Removes "f=" at the beginning. var $span = $( document.createElement('span') ); //Creates a span element to contain the new text. $span.addClass('filter'); //Adds the class filter to the span in case you would need to edit the styling. $span.text(" in "+'' + filter +'' + ".") //Inserts text and the value from the URL. $("h1").append($span) //Appends the new span to the existing string. });Pregunta: ¿Cómo puedo modificar el script para que solo informe el filtro si está seleccionado (si existe 'f=')?
¡Gracias por adelantado!
Simplemente puede usar la API de URL para analizar la URL en lugar de escribir una lógica personalizada para ella. URL.searchParams analizará todos los filtros de consulta en la URL y proporcionará una API adecuada para obtenerlos. Ver el código a continuación
$(document).ready(function() { const url = new URL(window.location.href); var filter = url.searchParams.get("f"); if (filter) { var $span = $(document.createElement('span')); //Creates a span element to contain the new text. $span.addClass('filter'); //Adds the class filter to the span in case you would need to edit the styling. $span.text(" in " + '' + filter + '' + ".") //Inserts text and the value from the URL. $("h1").append($span) //Appends the new span to the existing string. } });