刷新<div>元素时内容消失

问题描述 投票:0回答:1

我目前正在更新我的搜索引擎。我添加了过滤特定站点搜索结果的功能。为了做到这一点,使用 GCSE(Google 自定义搜索引擎),我将使用此处明确定义的

data-as_sitesearch
属性:https://developers.google.com/custom-search/docs/element#supported_attributes。当然,这些属性不能动态设置。因此,为了在用户单击按钮时更改搜索结果的来源,我必须使用以下方法设置此属性:
document.getElementById('searchresults').setAttribute('data-as_sitesearch', 'https://stackoverflow.com');
,然后使用 jQuery 刷新 GCSE 搜索结果元素的内容:
$('#searchresults').load(document.URL + ' #searchresults');
。 例如:

document.getElementById('stofSrch2').onclick = function (event) {
    document.getElementById('searchresults').setAttribute('data-as_sitesearch', 'https://stackoverflow.com');
    $('#searchresults').load(document.URL + ' #searchresults');
};

然而,这似乎不起作用。当我运行该函数时,div 的内容变为空白。如果这个解决方案不起作用,那么我该如何实现呢?当然,我也可以强制用户在搜索查询之前输入

site:https://stackoverflow.com
,但使用按钮更方便。

预先感谢您提供的任何帮助。

javascript jquery google-custom-search
1个回答
0
投票

如果您在 React 中使用 useState,则可能有其他一些函数将 div 的值设置为 null,每次刷新页面时都会由 useEffect 触发。

© www.soinside.com 2019 - 2024. All rights reserved.