我试图在单击复选框时将自定义搜索文本添加到谷歌搜索栏,并在删除该文本时删除所述文本。我已经弄清楚如何添加/删除文本区域中的文本以及如何将自定义文本放入搜索栏中,但是我在弄清楚如何用来自搜索栏中的文本替换搜索栏中的自定义文本时遇到了一些困难单击这些复选框时。
HTML
<body>
<div id="content">
<div id="search">
<gcse:search></gcse:search>
<div class="check_content">
<div class="checkbox">
<input type="checkbox" value="Value 1" id="checkbox1" name="checkbox" />
<label for="checkbox1" ></label>
</div>
<span>Value 1</span>
</div>
<div class="check_content">
<div class="checkbox">
<input type="checkbox" value="Value 2" id="checkbox2" name="checkbox" />
<label for="checkbox2" ></label>
</div>
<span>Value 1</span>
</div>
<div class="check_content">
<div class="checkbox">
<input type="checkbox" value="Value 3" id="checkbox3" name="checkbox" />
<label for="checkbox3" ></label>
</div>
<span>Value 1</span>
</div>
</div>
<textarea id="text"></textarea>
</div>
<strong>Google Search Bar with Custom Text</strong>
<script>
(function() {
var cx = '014565979167738564771:fixr4qj_zfs';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
window.onload = function(){
document.getElementById('gsc-i-id1').placeholder = 'This is custom text';
};
</script>
它位于结束正文标签的正上方。
将文本从复选框添加到 textarea 的函数
$("input[name=checkbox]").change(function() {
updateAllChecked();
});
function updateAllChecked() {
$('#text').text('');
$("input[name=checkbox]").each(function() {
if (this.checked) {
let old_text = $('#text').text() ? $('#text').text() + ', ' : '';
$('#text').text(old_text + $(this).val());
}
})
}
还包括 JS Fiddle - https://jsfiddle.net/2pdkv6ph/1/
您的代码有几个问题。首先,$(this).val()
不是复选框后面的跨度文本。您需要遍历 DOM 才能找到它。
$(this).parent('div').parent('div').find('span').text();
其次,您清除文本框然后尝试评估文本框中文本的顺序是向后的(您无法清除它然后检查它以查看“旧”文本是什么,因为您刚刚清除了它) .
A simpler approach would be to use an array, and when the checkbox is selected, push the span's text to the array. 循环后,将数组转换为逗号分隔的字符串并将该值分配给文本框。
function updateAllChecked() {
var myArray = [];
$("input[name=checkbox]").each(function() {
if (this.checked) {
var spanText= $(this).parent('div').parent('div').find('span').text();
myArray.push(spanText);
}
});
$('#text').text(myArray.join(", "));
//then assign to the Google text box?
document.getElementById('gsc-i-id1').value = myArray.join(", ");
}
注意:我不完全清楚您输入 id="text" 与 Google 搜索输入的目的是什么。所以,我已经展示了如何将跨度文本分配给两者。
这是一个小提琴演示:https : //jsfiddle.net/zephyr_hex/g97rzy2e/2/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句