gpt4 book ai didi

javascript - javascript点击后获取数组的下一个元素并将其显示在搜索表单中

转载 作者:行者123 更新时间:2023-11-30 12:07:32 24 4
gpt4 key购买 nike

我想创建 JS 代码,在执行某些操作后(例如单击后)将数组中的下一个元素放入表单中。

我想在访问某些网站时在控制台(firebug、firefox F12)中运行此代码。我创建了应该在 stackoverflow 上运行的代码测试示例,但它却没有,为什么?

示例 - stackoverflow.com:

单击标题区域 (id #question-header) 后,数组中的下一个元素应显示在搜索表单输入 (name q) 中。

当我在 firefox 控制台中运行代码时,它不起作用。

    var arr = ['foo', 'bar', 'baz'];
var i = 0;

function nextItem() {
i = i + 1; // increase i by one
i = i % arr.length; // if we've gone too high, start from `0` again
return arr[i]; // give us back the item of where we are now
}

window.addEventListener('load', function () {
document.getElementsByName('q').value = arr[0]; // initial value
document.getElementById('question-header').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementsByName('q').value = nextItem();
}
);
});

我该如何解决?

最佳答案

input 元素是自闭合标签,因此 textContent 不起作用。它的值可以通过 value 属性访问:

document.getElementById('search').value = nextItem();

更新:

根据问题更新,我认为您代码中的主要问题是您在页面加载时附加了监听器。将代码粘贴到浏览器控制台时无需执行此操作。这是关于 SO 的工作代码:

var arr = ['foo', 'bar', 'baz'];
var i = 0;

function nextItem() {
i = i + 1;
i = i % arr.length;
return arr[i];
}

// getElementsByName returns array of elements so access it by index
document.getElementsByName('q')[0].value = arr[0];

// because header contains inner link, add listener on it and prevent it from navigating
var header = document.getElementById('question-header');
var headerLink = header.getElementsByTagName('a')[0];

// when you pass code directly to console, page is (in most cases) already loaded
// you don't need to add listnener to 'load' event
headerLink.addEventListener(
'click',
function (e) {
document.getElementsByName('q')[0].value = nextItem();
e.preventDefault(); // prevent link to navigate
}
);

关于javascript - javascript点击后获取数组的下一个元素并将其显示在搜索表单中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34753781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com