0

さて、私はおそらく太っていますが、何かを機能させることができず、なぜ私を悩ませています. 私はJavascriptでグローバル置換プロパティを使用していますが、いつでも私がいるDIVの外では機能しません.

私が参加している DIV は、ターゲットにする必要があるものではありませんが、簡単な例を以下に示します。

<div id="foo">
<a href="http://www.somesite.com" target="_blank" class="footer">Site 1</a>
</div>

<script type="text/javascript">
window.onload =  function replaceScript() {
   var replacement = '<a href="http://www.somesite.com" target="_blank" class="footer">Site 1</a>';
var text = '<a href="http://www.othersite.com" title="Other Site" target="_blank">Site 2</a>';

document.getElementById("foo").innerHTML = text.replace(new RegExp(replacement, 'g'), '');

}
</script>

私が試していた別の方法はこれでした:

<script type="text/javascript">
window.onload = function replaceScript() {
var toReplace = '<a href="http://www.somesite.com" target="_blank" class="footer">Site 1</a>';
var replaceWith ='<a href="http://www.othersite.com" title="Other Site" target="_blank">Site 2</a>';
document.getElementById("foo") = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>

しかし、それをグローバルに機能させることはできません。

4

3 に答える 3

1

正規表現でこれをやりたいとは思いません。代わりに、このようにDOMメソッドを使用する必要があります

HTML

<div id="foo">
<a href="http://www.somesite.com" target="_blank" class="footer">Site 1</a>
</div>

Javascript

var fooA = document.getElementById("foo").children[0];

fooA.href = "http://www.othersite.com";
fooA.title = "Other Site";
fooA.firstChild.nodeValue = "Site 2";

結果

<div id="foo">
<a href="http://www.othersite.com" target="_blank" class="footer" title="Other Site">Site 2</a>
</div>

jsfiddleについて

于 2013-06-16T21:13:54.837 に答える
0

文字列比較を使用する代わりに、DOM 要素を使用する必要があります。これにより、より記述的であるため、より読みやすく、保守しやすいコードが作成されます。

var element = document.getElementById("foo"); 
var links = element.getElementsByTagName("a"); // get all links that are children of the div foo 
for (var i = 0; i < links.length; i++) { // Loop over the list
    if (links[i].getAttribute("href") == "http://www.somesite.com" ) { // Identify the link(s) we need to change
        links[i].setAttribute('href', 'http://otherside.com');
        links[i].setAttribute('title', 'Site2');

        links[i].innerHtml = 'Site2';
        // note that links[i].textContent would be better but it is not as cross browser compatible
    }
}

これには JavaScript フレームワークは必要ないことに注意してください。jQuery などのフレームワークを使用している場合は、これを単純化できる可能性があります。

于 2013-06-17T06:03:15.710 に答える
0

何をしようとしているのかわかりませんが、コードを変更するのは理にかなっています。

var child= document.querySelector("#foo a");
child.href="http://otherside.com"
child.title="Site2"
child.innerText= "Site2"

IE>=8 および他のすべてのブラウザで動作します。

于 2013-06-16T21:14:48.920 に答える