###前提・実現したいこと
現在Monacaを用いてアプリ開発の勉強をしていたのですが、element.setAttributeを用いてエレメントの属性を設定する動作を実装した際に、別のページにあるエレメントの属性を設定することができませんでした。
勉強不足な点もあるのですが、仕様なのか実装方法が悪いのかわからない状況です。
###該当のソースコード
page2にあるid="sample"のclass属性をnoからyesへ変更するソースです。
HTML
1<!DOCTYPE HTML> 2<html> 3<head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> 6 <meta http-equiv="Content-Security-Policy" content="default-src * data: gap: content: https://ssl.gstatic.com; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'"> 7 <script src="components/loader.js"></script> 8 <link rel="stylesheet" href="components/loader.css"> 9 <link rel="stylesheet" href="css/style.css"> 10</head> 11<body> 12<ons-navigator id="nav" page="page1.html"></ons-navigator> 13 14<template id="page1.html"> 15 <ons-page> 16 <ons-button id="push_css" onclick="document.getElementById('nav').pushPage('page2.html'),push_bt()">pushpage</ons-button> 17 </ons-page> 18</template> 19 20<template id="page2.html"> 21 <ons-page> 22 <div id="sample" class="no">属性変更</div> 23 <ons-button id="can_bt" onclick="document.getElementById('nav').popPage()">poppage</ons-button> 24 </ons-page> 25</template> 26 27<script type="text/javascript"> 28function push_bt(){ 29 var element = document.getElementById("sample"); 30 element.setAttribute("class", "yes"); 31 alert("change_txのrel属性は「"+element.getAttribute("class")+"」です"); 32} 33</script> 34</body> 35</html>
上記のソースのように別のページの属性を変更しようとすると何も反応しません。
下記のソースのようにボタンとelement.setAttributeを同一のページに実装すると属性の変更ができました。
HTML
1<!DOCTYPE HTML> 2<html> 3<head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> 6 <meta http-equiv="Content-Security-Policy" content="default-src * data: gap: content: https://ssl.gstatic.com; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'"> 7 <script src="components/loader.js"></script> 8 <link rel="stylesheet" href="components/loader.css"> 9 <link rel="stylesheet" href="css/style.css"> 10</head> 11<body> 12<ons-navigator id="nav" page="page1.html"></ons-navigator> 13 14<template id="page1.html"> 15 <ons-page> 16 <ons-button id="push_css" onclick="document.getElementById('nav').pushPage('page2.html'),push_bt()">pushpage</ons-button> 17 18 <div id="sample" class="no">属性変更</div> 19 </ons-page> 20</template> 21 22<script type="text/javascript"> 23function push_bt(){ 24 var element = document.getElementById("sample"); 25 element.setAttribute("class", "yes"); 26 alert("change_txのrel属性は「"+element.getAttribute("class")+"」です"); 27} 28</script> 29</body> 30</html> 31
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/09/15 06:48