2

javascript の関数から td の「onclick」の値を変更しようとしています。考えられることはすべて試しましたが、インターネットで検索しましたが、以下のコード以外は何も機能しませんでしたが、問題は、onclick の値を変更するのではなく、必要なものを実行していることです。 .

<div align="center" id="bodyC">
<table width="800" height="410">
<td class="bodyCC">
    <table id="MYtable" class="MYtable" border="0" width="100%" height="100%" cellpadding="50">
    <td id="one" class="one" onclick=""></td>
    <td id="two" class="two" onclick=""></td>
    <td id="three" class="three" onclick=""></td>
    </table>
</td>
</table>
</div>


function download()
{
<!-- this function is called when the "Download" button on the website's menu is pressed, and is soppused to change the "body" table so when the sells are clicked an alert will pop.-->
document.getElementById('one').onclick=alert("A..!");
document.getElementById('two').onclick=alert("B..!");
document.getElementById('three').onclick=alert("C..!");
}

助けはありますか?

ps エラーはありません。

4

1 に答える 1

8

あなたが書くとき

document.getElementById('one').onclick=alert("A..!");

onclickの戻り値をハンドラーとして設定しalert("A..!")ますundefined。したがって、これは機能しません。

必要なのは関数定義です:

document.getElementById('one').onclick = function() {alert("A..!");};

または、次のようにすることもできます。

function myfunc() {
    alert("A..!");
} 
document.getElementById('one').onclick = myfunc;

しかし、無名関数の定義を書くことは問題ありません。コードが使用される場所に保持され、多くの場合、よりクリーンになるからです。

また、スクリプト要素内に JavaScript を含める必要があります。

<script>
    document.getElementById('one').onclick = function() {alert("A..!");};
    document.getElementById('two').onclick = function() {alert("B..!");};
    document.getElementById('three').onclick = function() {alert("C..!");};
</script>

これは、ページの完全で修正済みのテスト済みバージョンです:

<div align="center" id="bodyC">
<table width="800" height="100"><tr>
<td class="bodyCC">
    <table id="MYtable" class="MYtable" border="0" width="100%" cellpadding="50"><tr>
    <td id="one" class="one" onclick="">ONE</td>
    <td id="two" class="two" onclick="">TWO</td>
        <td id="three" class="three" onclick="">THREE</td></tr>
    </table>
    </td></tr>
</table>
    <span onclick="download();">CLICK HERE</span>
</div>
<script>
// this function is called when the "Download" button on the website's menu
// is pressed, and is soppused to change the "body" table so when the sells
// are clicked an alert will pop.
function download() {
   document.getElementById('one').onclick=function(){alert("A..!");};
   document.getElementById('two').onclick=function(){alert("B..!");};
   document.getElementById('three').onclick=function(){alert("C..!");};
} 
</script>​​​​​​​​​​

(HTML コメントと欠落した tr も修正しました)

ここをクリックしてテストできます: 「ここをクリック」をクリックして、他の 3 つのセクション (1、2、3) をクリックする機能を有効にします。

于 2012-07-02T10:59:48.810 に答える