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.2k views
in Technique[技术] by (71.8m points)

jquery - Any Javascript GURU here to make this Script ? If Anchor is Changed Redirect the Page

Javascript expert,

i used a link in my own created templates...as you see the below ones:

<a href='http://www.allbloggertricks.com'>Blogging Tips</a>

No, i want if change the anchor text from Blogging Tips to any other then the page should be redirected to example.com .

Example: if the link become like this:

<a href='http://www.allbloggertricks.com'>Awesome Tips</a>

Now the page should be redirect to example.com because its anchor text changed from "Blogging Tips" to

"Awesome Tips"

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Not sure if you want the page to automatically redirect or to just have the URL changed dynamically. As you used the term 'redirect' I'll go with the first one. Run something like this once your page has loaded.

var anchorTags = document.getElementsByTagName("a");
var len = anchorTags.length;
while (len--) {
    var anchor = anchorTags[len];
    if (anchor.textContent === "Awesome Tips") {
        anchor.href = "http://example.com/";
        anchor.click();
    }
}

Hope that helped. :)


EDIT: Further to the comment below.

If I understand you correctly, you'll need to identify the specific anchor tag and then check to see if it's text is "Blogging Tips", or not. The first thing to do is give your target anchor tag a unique identification (id)...

<a href="http://..etc.." id="the_link">Blogging Tips</a>

Now you can easily find it with...

var theLink = document.getElementById('the_link');

You can then do a check similar to that suggestion above, but this time to see if the text is NOT 'Blogging Tips'...

if (theLink.textContent !== "Blogging Tips") {
   // .... do something ...
}

If you want to redirect the page the easiest thing to do is use window.location.assign(More on this at MDN).

You can only make this check once the page has loaded, so you'll need to wrap this inside a window.onload function or put it in a function that can be called once the page is loaded (More on this at MDN). Assuming the first option, the JavaScript now looks like this...

window.onload = function() {
  var theLink = document.getElementById("the_link");
  if (theLink.textContent !== "Blogging Tips") {
    window.location.assign("http://example.com/");
  }
};

However, if your template user removes or changes the anchor tag's id, or changes your JavaScript there is little you can do about it.

Hope that helped a bit more. :)


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

...