Javascript not working on clicked page of Onsen online UI
I am using Cordova / PhoneGap and Onsen frontend. I have two html pages. The pushpage button works perfectly. But Javascript doesn't work in search.html
Here is my code:
- index.html (default main page)
- search.html
index.html
...
<body>
<ons-navigator title="Navigator" var="myNavigator">
<ons-button
onclick="myNavigator.pushPage('search.html', { animation: 'lift' })">
Switch Page
</ons-button>
</ons-navigator>
</body>
search.html
<ons-page>
<script>
alert('Testing Javascript');
</script>
</ons-page>
source to share
The page is search.html
added dynamically when called myNavigator.pushPage('search.html')
.
When a tag is <script>
inserted this way, no code is executed.
Please refer to this question for more information: Is it possible to inject scripts using innerHTML?
To execute multiple script when the page is clicked you can use an event postpush
:
ons.ready(function() {
myNavigator.on('postpush', function() {
alert('Hello, world!');
});
});
source to share
It would be better if you put all JavaScript in js files and call the function when the button is clicked, for example:
Html
<body>
<ons-navigator title="Navigator" var="myNavigator">
<ons-button
onclick="myNavigator.pushPage('search.html', { animation: 'lift' }); callAlert();">
Switch Page
</ons-button>
</ons-navigator>
</body>
Js
Alternatively you can use events ons-navigator
, for example postpush
, to personalize your code even more, you can take a look at them HERE
source to share