2017-10-15 3 views
0

私は動的にjs関数でヘッダーの下にURLを変更しようとしています。残念ながら私は簡単な部分に積み重ねています。JSのヘッダーの下のURLの変更

linkによると、私は...その問題を解決するために私のコードの

簡易版試してみました:

<div class="details"> 
    <h1 id="title">Old title</h1> 
    <h3 id="author"> 
    <a id="aId" href="https://www.google.pl/">Old author</a> 
    </h3> 
</div> 

をスクリプト:

var title = $("#title");// the id of the heading 
var author = $("#author");// id of author 

title.text("New title"); 
author.text("New author"); 
var a = document.getElementById('aId'); 
a.href = "bing.com" 

問題は、著者が今はないということですクリック可能。私たちを手伝ってくれますか?

EDIT:あなたの助けを

ありがとう! ソリューション:

var title = $("#title");// the id of the heading 
var author = $("#author a");// id of author 

title.text("New title"); 
author.text("New author"); 
author.attr("href", "http://bing.com") 

答えて

2

あなたがauthor.text("New author");を呼び出し、あなたは<h3 id="author">要素内のリンクのフォームを削除しています。次のようにあなたは、代わりに直接h3のリンク内の著者の名前を変更する必要があります

<h3 id="author">New author</h3> 

<h3 id="author"> 
    <a id="aId" href="https://www.google.pl/">Old author</a> 
</h3> 

var title = $("#title");// the id of the heading 
var author = $("#author a");// id of author 

title.text("New title"); 
author.text("New author"); 
var a = document.getElementById('aId'); 
a.href = "http://bing.com" 

ペイ特別な基本的からそれを行きます著者のセレクタが#author要素内のa要素に変更されていることに注意してください。

あなたがここにコードをテストすることができます(3秒待ってから、あなたが更新されているリンクが表示されます)

https://jsfiddle.net/nq8hwr2x/

+0

ありがとうございました。それは働いていますが、本当に2つの識別子が必要ですか? '#author a'や 'ald'のようなものですか?よりエレガントな方法はありますか? – Misiek777

+1

もっとエレガントな方法がありますが、変更を最小限に抑えようとしました。 'author.text(" New author ")。attr(" href "、" http://bing.com ");'を実行して、すべての変更を1行で行うことができます。 –

2

問題がある<h3>タグ、内側<a>タグをネストされていることですtext属性を変更するとリンクが削除されます。あなただけの<h3>タグを失い、直接<a>テキストを設定することができます:あなたが答えるために

$("#title").text("New title"); 
 
$("#aId").text("New author").attr("href", "http://bing.com/");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="details"> 
 
    <h1 id="title">Old title</h1> 
 
    <a id="aId" href="https://www.google.pl/">Old author</a> 
 
</div>

関連する問題