jQuery 使用锚点的 class 名称将锚点的 href 值动态设置为另一个锚点的 href 值
jQuery dynamically set href value of an anchor to the href value of another anchor using their class names
我在 hubspot 上有一个基于搜索词查询动态生成的搜索列表页面。
HTML结构如下:
<div class="search-listing">
a class="hs-search-results__title" href="www.something.com"><img src="Some image"></a>
<a class="more-link">Read More</a>
</div>
现在该页面有一些这样的 .search-listing div。我希望每个 .search-listing 中 more-link
的 href 取每个搜索列表 hs-search-results__title
link 中 href 的值。
加法:
这是首先用于将值赋给 hs-search-results__title 的代码。也许这会有所帮助?
HTML:
<div class="hs-search-results2">
<template class="hs-search-results__template">
<li>
<div class="hs-search-results__featured-image">
<a href="#"><img src=""></a>
</div>
<a href="#" class="hs-search-results__title">Content Title</a>
<p class="hs-search-results__description">Description</p>
<p>
<a class="more-link" href="#" style="color: #FFF!important">Read More</a>
</p>
</li>
</template>
<ul id="hsresults" class="hs-search-results__listing"></ul>
<div class="hs-search-results__pagination" data-search-path="{{ site_settings.content_search_results_page_path }}">
<a href="" class="hs-search-results__prev-page"></a>
<a href="" class="hs-search-results__next-page"></a>
</div>
</div>
jQuery:
var hsResultsPage = function(_resultsClass) {
function buildResultsPage(_instance) {
var resultTemplate = _instance.querySelector('.hs-search-results__template'),
resultsSection = _instance.querySelector('.hs-search-results__listing'),
searchPath = _instance.querySelector('.hs-search-results__pagination').getAttribute('data-search-path'),
prevLink = _instance.querySelector('.hs-search-results__prev-page'),
nextLink = _instance.querySelector('.hs-search-results__next-page');
var searchParams = new URLSearchParams(window.location.search.slice(1));
function getTerm() {
return searchParams.get('term') || "";
}
function getOffset() {
return parseInt(searchParams.get('offset')) || 0;
}
function getLimit() {
return parseInt(searchParams.get('limit'));
}
function addResult(title, url, description, featuredImage) {
var newResult = document.importNode(resultTemplate.content, true);
function isFeaturedImageEnabled() {
if (newResult.querySelector('.hs-search-results__featured-image img')) {
return true;
}
}
newResult.querySelector('.hs-search-results__title').innerHTML = title;
newResult.querySelector('.hs-search-results__title').href = url;
newResult.querySelector('.hs-search-results__featured-image a').href = url;
newResult.querySelector('.hs-search-results__description').innerHTML = description;
if (typeof featuredImage !== 'undefined' && isFeaturedImageEnabled()) {
newResult.querySelector('.hs-search-results__featured-image img').src = featuredImage;
}
resultsSection.appendChild(newResult);
}
function fillResults(results) {
results.results.forEach(function(result, i){
addResult(result.title, result.url, result.description, result.featuredImageUrl);
});
}
function emptyPagination() {
prevLink.innerHTML = "";
nextLink.innerHTML = "";
}
function emptyResults(searchedTerm) {
resultsSection.innerHTML = "<div class=\"hs-search__no-results\"><p>Sorry. There are no results for \"" + searchedTerm + "\"</p>" +
"<p>Try rewording your query, or browse through our site.</p></div>";
}
function setSearchBarDefault(searchedTerm) {
var searchBars = document.querySelectorAll('.hs-search-field__input');
Array.prototype.forEach.call(searchBars, function(el){
el.value = searchedTerm;
});
}
function httpRequest(term, offset) {
var SEARCH_URL = "/_hcms/search?",
requestUrl = SEARCH_URL + searchParams + "&analytics=true",
request = new XMLHttpRequest();
request.open('GET', requestUrl, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
setSearchBarDefault(data.searchTerm);
if (data.total > 0) {
fillResults(data);
paginate(data);
}
else {
emptyResults(data.searchTerm);
emptyPagination();
}
}
else {
console.error('Server reached, error retrieving results.');
}
};
request.onerror = function() {
console.error('Could not reach the server.');
};
request.send();
}
function paginate(results) {
var updatedLimit = getLimit() || results.limit;
function hasPreviousPage() {
return results.page > 0;
}
function hasNextPage() {
return results.offset <= (results.total - updatedLimit);
}
if (hasPreviousPage()) {
var prevParams = new URLSearchParams(searchParams.toString());
prevParams.set('offset', (results.page * updatedLimit) - parseInt(updatedLimit));
prevLink.href = "/" + searchPath + "?" + prevParams;
prevLink.innerHTML = "< Previous page";
}
else {
prevLink.parentNode.removeChild(prevLink);
}
if (hasNextPage()) {
var nextParams = new URLSearchParams(searchParams.toString());
nextParams.set('offset', (results.page * updatedLimit) + parseInt(updatedLimit));
nextLink.href = "/" + searchPath + "?" + nextParams;
nextLink.innerHTML = "Next page >";
}
else {
nextLink.parentNode.removeChild(nextLink);
}
}
var getResults = (function() {
if (getTerm()) {
httpRequest(getTerm(), getOffset());
}
else {
emptyPagination();
}
})();
}
(function() {
var searchResults = document.querySelectorAll(_resultsClass);
Array.prototype.forEach.call(searchResults, function(el){
buildResultsPage(el);
});
})();
}
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
var resultsPages = hsResultsPage('.hs-search-results2');
}
else {
document.addEventListener('DOMContentLoaded', function() {
var resultsPages = hsResultsPage('.hs-search-results2');
});
}
可以遍历所有search-listing
,在元素里面找到对应的元素get/set属性。
尝试以下方式:
$('.search-listing').each(function(){
var searchHref = $(this).find('.hs-search-results__title').attr('href');
$(this).find('.more-link').attr('href', searchHref)
});
a img{
width:25px;
height: auto;
border: 1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="search-listing">
<a class="hs-search-results__title" href="https://whosebug.com/"><img src="https://cdn.sstatic.net/Sites/Whosebug/company/img/logos/so/so-icon.png?v=c78bd457575a"></a>
<a class="more-link">Read More</a>
</div>
<div class="search-listing">
<a class="hs-search-results__title" href="https://google.com/"><img src="https://cdn4.iconfinder.com/data/icons/new-google-logo-2015/400/new-google-favicon-512.png"></a>
<a class="more-link">Read More</a>
</div>
我在 hubspot 上有一个基于搜索词查询动态生成的搜索列表页面。
HTML结构如下:
<div class="search-listing">
a class="hs-search-results__title" href="www.something.com"><img src="Some image"></a>
<a class="more-link">Read More</a>
</div>
现在该页面有一些这样的 .search-listing div。我希望每个 .search-listing 中 more-link
的 href 取每个搜索列表 hs-search-results__title
link 中 href 的值。
加法:
这是首先用于将值赋给 hs-search-results__title 的代码。也许这会有所帮助?
HTML:
<div class="hs-search-results2">
<template class="hs-search-results__template">
<li>
<div class="hs-search-results__featured-image">
<a href="#"><img src=""></a>
</div>
<a href="#" class="hs-search-results__title">Content Title</a>
<p class="hs-search-results__description">Description</p>
<p>
<a class="more-link" href="#" style="color: #FFF!important">Read More</a>
</p>
</li>
</template>
<ul id="hsresults" class="hs-search-results__listing"></ul>
<div class="hs-search-results__pagination" data-search-path="{{ site_settings.content_search_results_page_path }}">
<a href="" class="hs-search-results__prev-page"></a>
<a href="" class="hs-search-results__next-page"></a>
</div>
</div>
jQuery:
var hsResultsPage = function(_resultsClass) {
function buildResultsPage(_instance) {
var resultTemplate = _instance.querySelector('.hs-search-results__template'),
resultsSection = _instance.querySelector('.hs-search-results__listing'),
searchPath = _instance.querySelector('.hs-search-results__pagination').getAttribute('data-search-path'),
prevLink = _instance.querySelector('.hs-search-results__prev-page'),
nextLink = _instance.querySelector('.hs-search-results__next-page');
var searchParams = new URLSearchParams(window.location.search.slice(1));
function getTerm() {
return searchParams.get('term') || "";
}
function getOffset() {
return parseInt(searchParams.get('offset')) || 0;
}
function getLimit() {
return parseInt(searchParams.get('limit'));
}
function addResult(title, url, description, featuredImage) {
var newResult = document.importNode(resultTemplate.content, true);
function isFeaturedImageEnabled() {
if (newResult.querySelector('.hs-search-results__featured-image img')) {
return true;
}
}
newResult.querySelector('.hs-search-results__title').innerHTML = title;
newResult.querySelector('.hs-search-results__title').href = url;
newResult.querySelector('.hs-search-results__featured-image a').href = url;
newResult.querySelector('.hs-search-results__description').innerHTML = description;
if (typeof featuredImage !== 'undefined' && isFeaturedImageEnabled()) {
newResult.querySelector('.hs-search-results__featured-image img').src = featuredImage;
}
resultsSection.appendChild(newResult);
}
function fillResults(results) {
results.results.forEach(function(result, i){
addResult(result.title, result.url, result.description, result.featuredImageUrl);
});
}
function emptyPagination() {
prevLink.innerHTML = "";
nextLink.innerHTML = "";
}
function emptyResults(searchedTerm) {
resultsSection.innerHTML = "<div class=\"hs-search__no-results\"><p>Sorry. There are no results for \"" + searchedTerm + "\"</p>" +
"<p>Try rewording your query, or browse through our site.</p></div>";
}
function setSearchBarDefault(searchedTerm) {
var searchBars = document.querySelectorAll('.hs-search-field__input');
Array.prototype.forEach.call(searchBars, function(el){
el.value = searchedTerm;
});
}
function httpRequest(term, offset) {
var SEARCH_URL = "/_hcms/search?",
requestUrl = SEARCH_URL + searchParams + "&analytics=true",
request = new XMLHttpRequest();
request.open('GET', requestUrl, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
setSearchBarDefault(data.searchTerm);
if (data.total > 0) {
fillResults(data);
paginate(data);
}
else {
emptyResults(data.searchTerm);
emptyPagination();
}
}
else {
console.error('Server reached, error retrieving results.');
}
};
request.onerror = function() {
console.error('Could not reach the server.');
};
request.send();
}
function paginate(results) {
var updatedLimit = getLimit() || results.limit;
function hasPreviousPage() {
return results.page > 0;
}
function hasNextPage() {
return results.offset <= (results.total - updatedLimit);
}
if (hasPreviousPage()) {
var prevParams = new URLSearchParams(searchParams.toString());
prevParams.set('offset', (results.page * updatedLimit) - parseInt(updatedLimit));
prevLink.href = "/" + searchPath + "?" + prevParams;
prevLink.innerHTML = "< Previous page";
}
else {
prevLink.parentNode.removeChild(prevLink);
}
if (hasNextPage()) {
var nextParams = new URLSearchParams(searchParams.toString());
nextParams.set('offset', (results.page * updatedLimit) + parseInt(updatedLimit));
nextLink.href = "/" + searchPath + "?" + nextParams;
nextLink.innerHTML = "Next page >";
}
else {
nextLink.parentNode.removeChild(nextLink);
}
}
var getResults = (function() {
if (getTerm()) {
httpRequest(getTerm(), getOffset());
}
else {
emptyPagination();
}
})();
}
(function() {
var searchResults = document.querySelectorAll(_resultsClass);
Array.prototype.forEach.call(searchResults, function(el){
buildResultsPage(el);
});
})();
}
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
var resultsPages = hsResultsPage('.hs-search-results2');
}
else {
document.addEventListener('DOMContentLoaded', function() {
var resultsPages = hsResultsPage('.hs-search-results2');
});
}
可以遍历所有search-listing
,在元素里面找到对应的元素get/set属性。
尝试以下方式:
$('.search-listing').each(function(){
var searchHref = $(this).find('.hs-search-results__title').attr('href');
$(this).find('.more-link').attr('href', searchHref)
});
a img{
width:25px;
height: auto;
border: 1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="search-listing">
<a class="hs-search-results__title" href="https://whosebug.com/"><img src="https://cdn.sstatic.net/Sites/Whosebug/company/img/logos/so/so-icon.png?v=c78bd457575a"></a>
<a class="more-link">Read More</a>
</div>
<div class="search-listing">
<a class="hs-search-results__title" href="https://google.com/"><img src="https://cdn4.iconfinder.com/data/icons/new-google-logo-2015/400/new-google-favicon-512.png"></a>
<a class="more-link">Read More</a>
</div>