Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

javascript - How to change the name field of an <input> in an AJAX-driven page?

For this target page (Sorry but SO doesn't allow hyperlinks to 62.0.54.118):

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

, I want to change the name field of an <input> by default with a userscript.

The input is:

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

I want to change it to:

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


That is, I Want to change the q into &q in the name field of the input by default.

I try to write a script, (that doesn't work):

// ==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;
}


In addition, the page is an Ajax-driven page.

Please fix my bad script or help me to write another one, Thanks.

Update: I solved a part of that by changing a line of my script from:

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

to

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

and then my script works better. Thanks to @Gerard Sexton for suggesting that.

But there is a new bug now, with the waitForKeyElements callback set to return true; for the page's AJAX, It adds the & non stop.

It causes this field to be name="&&&&&&&&&q", etc.

How can I fix it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If the input name is just q, by itself, then merely change the waitForKeyElements call to:

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

So that it looks for exactly q, rather than a q anywhere in the string.


If that's not exactly the name of that <input>, comment below.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...