【问题标题】:How to change the name field of an <input> in an AJAX-driven page?如何在 AJAX 驱动的页面中更改 <input> 的名称字段?
【发布时间】:2013-10-24 12:43:01
【问题描述】:

对于此目标页面(抱歉,SO 不允许超链接到 62.0.54.118):

http://62.0.54.118/search?&q=42&oq=42&sourceid=chrome&ie=UTF-8&filter=0

,我想默认使用用户脚本更改&lt;input&gt; 的名称字段。

输入是:

<input class="gsfi" id="lst-ib" name="q" maxlength="2048" value="42"...>

我想改成:

<input class="gsfi" id="lst-ib" name="&q" maxlength="2048" value="42"...>


也就是我想把输入的name字段中的q默认改成&amp;q

我尝试写一个脚本,(那行不通):

// ==UserScript==
// @name     Normal Google Input
// @include  http://62.0.54.118/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
waitForKeyElements ("input[name*='q']", changeLinkQuery);

function changeLinkQuery (jNode) {
    var oldName = jNode.attr ('name');
    var newName = oldName.replace (/\q/, "&q");

    jNode.attr ('name', newName);

    return true;
}


此外,该页面是一个 Ajax 驱动的页面。

请修复我的错误脚本或帮助我编写另一个脚本, 谢谢。

更新: 我通过将脚本的一行从以下内容更改为解决了部分问题:

var newName = oldName.replace (/\q/, "&q");

var newName = oldName.replace (/q/, "&q");

然后我的脚本效果更好。感谢@Gerard Sexton 的建议。

但是现在有一个新错误,将页面的 AJAX 的 waitForKeyElements 回调设置为 return true;,它添加了 &amp; 不间断。

导致该字段为name="&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;q"

我该如何解决?

【问题讨论】:

  • 将您的正则表达式更改为 /q/
  • 谢谢,它成功了
  • 我做到了,但我仍然有脚本的错误:return true;,对于 ajax,使&amp; 不停地添加导致该字段成为name="&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;q" 的原因跨度>
  • “静态 Ajax 驱动页面”有点矛盾。通常,如果页面包含任何由 AJAX 驱动的重要内容,则该页面被视为 AJAX 驱动,即使它可能包含静态元素。
  • @reemar 听起来好像 changeLinkQuery 函数被多次调用。也许 waitForKeyElements 会为每个匹配选择器的元素调用回调。

标签: javascript ajax google-chrome userscripts tampermonkey


【解决方案1】:

如果输入名称本身只是q,那么只需将waitForKeyElements调用更改为:

waitForKeyElements ("input[name='q']", changeLinkQuery);

所以它准确地寻找q,而不是字符串中的任何地方的q。


如果这不是 确切&lt;input&gt; 的名称,请在下方评论。

【讨论】:

    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 2010-11-09
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2014-01-09
    • 1970-01-01
    相关资源
    最近更新 更多