get href of button and img - javascript

i am no little knowledge about js and html,i have a html like:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>aa</title>
</head>
<body><input name="button" type="button" value="hello" onclick="window.location.href('http://hao.360.cn/')" />
<input name="button" type="submit" value="helio" onclick="window.open('http://hao.360.cn/')"/>
<body bgcolor="#000000">
<img src="a2.jpg" width="156" height="152" border="0" longdesc="eclipse.exe.lnk" />
</body>
</html>
i want to using js to get respectively the string http://hao.360.cn/ of the two buttons and also get the string fg726p.exe and eclipse.exe.lnk of img?
i want to using the js to get the values for android java methods. i want to get help.
edit: through some people think it is so basic,butfor me i know clue to search it
can you give me some advice and link
edit2: i adjust :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>aa</title>
<script language="javascript">
function get(){
var xx=document.getElementById("bbs")
alert(":"+xx.title);
}
function getElementName(){
var ele = document.getElementById("link1");
alert(":" + ele.href);
}
</script>
<body><input name="button" id="bbs" title="http://homepage.yesky.com/59/2673059.apk" type="button" value="hello" onclick="get()" />
<input name="button2" type="submit" value="helio" onclick="getElementName()"/>
<body bgcolor="#000000">
<img src="a2.jpg" width="156" height="152" border="0" onclick="getElementName()" />
</body>
</html>
i have solved my problem,but i donot know why somepeople post Negative Scores give me for no little js knowledge.may be you know more,think this easy. i only want to
get the sting to use,i think if you know more you only answer document.getElementById("link1").href also can help me not give me all the html document. i want to string to use for my android app, i think i donot because the small problem to study the all html. the project not give you more time
edit3:
var x=document.getElementsByTagName("input");
var el =x.item(0);
alert(el.getAttribute("value"));
alert(el.getAttribute("onclick"));
el =x.item(1);
alert(el.getAttribute("value"));
alert(el.getAttribute("onclick"));
x=document.getElementsByTagName("a");
el =x.item(0);
alert(el.getAttribute("href"));
x=el.getElementsByTagName("img");
el =x.item(0);
alert(el.getAttribute("longdesc"));​
thank you #jmoreno for this answer for my frist question very good.i put answer here so that prevent the link of he give is broken .

If you are generating that HTML, be aware it has a couple of problems with it. 1) JavaScript and DOM manipulation work best when specific tags have id's, 2) the body tag is present twice.
But within the limits of what you have posted, see this jsfiddle.
The heart of it being the ...getAttribute("onclick") where given a element in the DOM, you get the required attribute (onclick, href, longdesc).
I leave it to you to parse out the sub string you want.

You code seems to be a little messed up.
You are using body 2 times. Setting the bgcolor as you do is really old fashioned, when you want to set the background color inline, which I would not recommend you to do you are doing it this way style="background-color:#000000;". You really should use an external css file. Because in my opinion HTML is for the markup and css is for the styling, and if you have to change the layout in the future you don't know if you have set the styling in the css or in the html. So try to stick one method. Also never ever use body 2 times.
Give your input fields an ID so you could easily access them via javascript, or as you tagged your question jQuery but reading through your HTML Markup, I can see that you have not included jQuery yet.
Examples of using jQuery to get the values you want. As you have seen I have edited your html markup a bit, so its cleaner and has more structure:
http://jsfiddle.net/pmjVP/

Related

Making live python compiler inside a HTML page using PyScript

I want to build a live Pythonn compiler similar to those at w3schools for Python, for some examples on my blog. I tried different approaches, and would like to hear different oppinions, but as of yesterday I'm trying to implement it using PyScript.
The documentation I found for PyScript doesn't help me a lot, as it seems like I can't understand it, or doing something wrong.
Here's the code that I'm trying to implement:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Writing to the page</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<textarea id="area1" rows="15">something</textarea>
<button onclick="myFunction()">Click me</button>
<py-script id="demo">
print("Hello, world!")
</py-script>
<py-terminal></py-terminal>
<script>
function myFunction() {
var text1 = document.getElementById('area1').value;
document.getElementById("demo").innerHTML = text1;
}
</script>
</body>
</html>
It just prints the content of the textarea above the terminal, without executing the code and printing the output, inside the terminal, as I imagined.
I'm expecting to make this functinal, and I tried a few things, but unsuccessfully.
I also tried:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Writing to the page</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<textarea id="area1" rows="15">print("something")</textarea>
<script>
let text1 = document.getElementById('area1').value;
</script>
<py-script>
def print_to_page(x):
exec(x)
</py-script>
<button py-click="print_to_page(text1)" id="print">Run!</button>
</body>
</html>
But I'm not sure how to pass the variable from JS to PyScript.
This 'Answer' is meant to help in addressing:
"I tried different approaches, and would like to hear different oppinions [sic],"
You may want to check out this post:
https://twitter.com/jtpio/status/1523660682708668416 May 2022
"The #SymPy Online Shell is now powered by the #pyodide stack and JupyterLite💡
You can try the latest SymPy release directly in your browser, without installing anything, by visiting the following URL:
https://sympy.org/en/shell.html
Many thanks to Ivan Savov for leading this effort!"
Something like that may integrate well with your blog. You can hack around on it and hopefully put together what you need combined with that example and the documentation.
Related resources:
'Embedding the REPL on another website' section in the JupyterLite documentation
Embedding Jupyter Everywhere - Easily embed a console, a notebook, or a fully-fledged IDE on any web page.
Alternative approaches:
JupyterBook and MyST-NB seems to be moving along this route. For example see the Render option the left side there.
I'm not sure all the pieces are together but you can imagine with the JupyterLite/pyodide stuff it soon will be set for blogs.) Quarto may be heading that way, too.
See also Make Jupyter notebook executable in html format
Based on your description and the second example, it looks like you want to have a textarea where the user types in Python code, and run button that executes that entered code when clicked. If I've misunderstood your goal, you can disregard this answer.
The way to bring JavaScript objects/variables into Python is using Pyodide's import js syntax, which treats the JavaScript global namespace like a Python module. Here's a version very similar to your second example, which imports JavaScript's document object and uses that to extract the value of the textarea:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Writing to the page</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>
<body>
<textarea id="area1" rows="15">print("something")</textarea>
<py-script>
from js import document
def runTextInTag(id):
src = document.getElementById(id).value
exec(src)
</py-script>
<button py-click="runTextInTag('area1')" id="run">Run!</button>
</body>
To address your first example, which changes the innerHTML of the py-script tag itself: A <py-script> tag executes its contained code exactly once, when the custom element is attached to the DOM. This happens shortly after PyScript initializes and the custom HTML element <py-script> is defined, or when you add an additional <py-script> tag to the page.So, in your first example, setting the innerHTML/innerTEXT of a <py-script> tag does not cause that code to be executed again.
You could create a new <py-script> tag with the appropriate innerText and add it to the DOM, at which point its code would be executed, but I think the above method is cleaner for most purposes.

How to think of Javascript-is this accurate?

I'm working through some javascript examples, and I just did this one:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Page title</title>
<script type="text/javascript">
function displayText()
{
document.getElementById('targetDIV').innerHTML = "You're using Javascript";
}
</script>
</head>
<body onload="displayText()">
<h2>This should be before the other text.</h2>
<div id="targetDIV">
</div>
</body>
</html>
OK. Very basic, I know-but I realized I was confused about the "why" of some things. Could it be accurate to say that:
Function=WHAT will happen.
The call (the body onload...)= WHEN it will happen.
and div id="targetDIV" = WHERE it will happen
I know this is the case in this example, but in general is that the way things work in Javascript?
Yes, that's a pretty good working model to carry in your head.
onload for the body is called an Event and many objects issue events. Your function displayText is called in response to the onload Event and is therefore an event handler.
The code inside your function can do anything, but in this case it dynamically loads some text into a tag on your page.
There are a couple of other things worth pointing out at this point. You access the tag using document.getElementById. document is variable available to you in Javascript which contains a model of the page called the DOM or document object model. This is extremely powerful as it presents a hierarchical layout of everything on your page and allows you to manipulate the contents.
getElementById() is a very useful function which searches the DOM tree and returns the object which has the ID that you specify, it's a sort of search. The text gets to your tag because you added the targetDIV id to the DIV tag and therefore you could find it via the DOM function.
Welcome to programming in Javascript. Now you have a goood working model you'll find loads of really clever things you can do and your life as a web programmer will never be the same again.
Sound good to me.

How to get scripts to fire that are embedded in content retrieved via the jquery load() method?

I have found several other questions here on S.O. (and the web in general) that ask roughly this same question, but the answers always seem to suggest other ways of structuring code that avoid the need for addressing this underlying issue.
For example, many people suggest (and a good suggestion, I agree) to put your code in the jquery load method's callback, on the calling page and not the called page. However I have unique scripts that may appear in certain resources, so I would not want to do that for every load and nor do I necessarily know what these scripts will be.
Here is a test setup to demonstrate what I'm trying to do. The short summary is that when I load partial.htm from main.htm, its script does not fire.
main.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>main file</title>
</head>
<body>
<ul id="links">
<li>some page1</li>
<li>some page 2</li>
<li>some other partial page</li>
</ul>
<div id="panel" style="display:none; padding:20px; background-color:#CCC;">
LOADED CONTENT WILL GO HERE
</div>
<script type="text/javascript" src="/path/to/jquery-1.3.2.min.js"> </script>
<script type="text/javascript">
$(function(){
$('#links a').click(function() {
var $panel = $('#panel');
$panel.show();
$panel.html('Please wait...');
var href = $(this).attr('href');
$('#panel').load(href + ' #content');
return false;
});
});
</script>
</body>
</html>
OK, very simple functionality on this page. Imagine there are many more links, and some of them may require scripting while others do not.
Here is partial.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>partial file</title>
</head>
<body>
<div id="content">
<p>Hey, I am the partial file!</p>
<script type="text/javascript">
alert('I am some JS in the partial file! But sadly I do not execute...');
</script>
</div>
<div>
I am some other content on the page that won't be included by jquery.load()...
</div>
</body>
</html>
Notice that my script in partial.htm does not fire. So, my question remains: how to get this to fire, excluding any answers that tell me to put this in the .load() method's callback. (This would be because I may not have the fore-knowledge of which scripts these partial pages may contain or require!)
Thank you!
Update #1:
I suppose an acceptable answer is simply "you can't." However, I'd like to know if this is definitively the case. I haven't been able to find anything that officially states this yet.
Also, when I use firebug to inspect the panel region afterwards, there is no script element present at all. It is as if it is being parsed out by load.
Update #2:
I've narrowed this down to be a problem only when using the selector as part of the href. Loading the entire "somepage.html" will execute the script, but loading "somepage.html #someregion" does not.
$panel.load('somepage.html'); // my script fires!
$panel.load('somepage.html #someregion'); // script does not fire
I'm going to try and hunt down why this may be the case in the jquery source...
Well it seems that this is by design. Apparently to make IE happy, the rest of us suffer. Here's the relevant code in the jquery source:
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div/>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
I'm wondering if, instead of just stripping out the scripts, I could modify the jquery source to include them in some other way that makes IE happy? I still have yet to find anything else on the web discussing this matter, I'm sure I'm not the only person stumped by this?
I have run across issues before with IE not running injected <script>s that didn't contain the defer attribute. This discussion thread has some good information about the topic: innerHTML and SCRIPT tag

How does the location of a script tag in a page affect a JavaScript function that is defined in it?

I read that you should define your JavaScript functions in the <head> tag, but how does the location of the <script> (whether in the <head>, <body>, or any other tag) affect a JavaScript function.
Specifically, how does it affect the scope of the function and where you can call it from?
Telling people to add <SCRIPT> only in the head sounds like a reasonable thing to do, but as others have said there are many reasons why this isn't recommended or even practical - mainly speed and the way that HTML pages are generated dynamically.
This is what the HTML 4 spec says :
The SCRIPT element places a script
within a document. This element may
appear any number of times in the HEAD
or BODY of an HTML document.
And some sample HTML. Doesn't it look pretty all formatted here :)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<SCRIPT type="text/vbscript" src="http://someplace.com/progs/vbcalc">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
...some JavaScript...
</SCRIPT>
</BODY>
</HTML>
And something to look forward to in HTML 5 :
New async attribute in <SCRIPT> :
Note: There are ways [sic] a script can be
executed:
The async attribute is "true": The
script will be executed asynchrously
with the rest of the page, so the
script will be executed while the page
continues the parsing.
The async attribute is "false", but
the defer attribute is "true": The
script will be executed when the page
is finished with the parsing.
The normal rules of play still stand; don't use stuff before it's defined. :)
Also, take note that the 'put everything at the bottom' advice isn't the only rule in the book - in some cases it may not be feasible and in other cases it may make more sense to put the script elsewhere.
The main reason for putting a script at the bottom of a document is for performance, scripts, unlike other HTTP requests, do not load in parallel, meaning they'll slow down the loading of the rest of your page. Another reason for putting scripts at the bottom is so you don't have to use any 'DOM ready' functions. Since the script tag is below all elements the DOM will be ready for manipulation!
EDIT: Read this: http://developer.yahoo.com/performance/rules.html#js_bottom
One of the aspects of placement is performance. See this fine article within the YSlow discussion for why it's sometimes recommended you put them at the bottom of the document.
As for issues of scope, the usual visibility rules for Javascript (vars defined inside or outside of functions, local, global, closures, etc.) are not affected so far as I know.
Position of script tag does matter.
If you bind a Function with document Element then the document element has to be loaded first before we implement function. suppose getTeachers() is function in getTeachers.js file.
This will give you an error:
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Unit Teachers</title>
<head>
<script type="text/javascript" src="getTeachers.js"></script>
<script type="text/javascript">
document.getElementById("buttonId").onclick=function(){getResults()};
</script>
</head>
<body>
<form>
<input type = "button" id="buttonId" value = "Press for Results" /><br />
</form>
<span id="results" /></span>
</body>
</html>
It gives error before head is loaded first and it cannot find element with id specified.
The below code is correction:
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Unit Teachers</title>
<head>
<script type="text/javascript" src="getTeachers.js"></script>
</head>
<body>
<form>
<input type = "button" id="buttonId" value = "Press for Results" /><br />
</form>
<script type="text/javascript">
document.getElementById("buttonId").onclick=function(){getResults()};
</script>
<span id="results" /></span>
</body>
</html>
If your script refers to an ID on the page and the page has not been rendered (i.e. script is before HTML, or your script is executed with onload, rather then the DOM is ready) you can also get an error.
It doesn't. Most programming framework scatter scripts all throughout the page. I've only rarely seen problems because of that (and only from older browsers).
If you pull Javascripts in through XMLHttpRequest, like Diodeus said, it probably won't work. In my case, there was no error, the browser just ignores the new script(s).
I ended up using this, not terribly elegant but works for me so far:
http://zeta-puppis.com/2006/03/07/javascript-script-execution-in-innerhtml-the-revenge/
How to use execJS: http://zeta-puppis.com/2006/02/23/javascript-script-execution-in-innerhtml/
Note: Watch out for < in this line: for(var i=0;i<st.length; i++)
If you have an inline script (outside functions) located before functions it may call, you may get an error because they may not be not available yet. Not saying it is always going to happen, just that it may depending on browser type or version.
Javascript's scoping rules are similar to perl - you can call any function at the current or any higher scope level. The only restriction is that the function has to be defined at the time you call it. The position in the source is irrelevant - only the position in time matters.
You should avoid putting scripts in the <head> if possible as it slows down page display (see the link Alan posted).

A issue with the jquery dialog when using the themeroller css

The demos for the jquery ui dialog all use the "flora" theme. I wanted a customized theme, so I used the themeroller to generate a css file. When I used it, everything seemed to be working fine, but later I found that I can't control any input element contained in the dialog (i.e, can't type into a text field, can't check checkboxes). Further investigation revealed that this happens if I set the dialog attribute "modal" to true. This doesn't happen when I use the flora theme.
Here is the js file:
topMenu = {
init: function(){
$("#my_button").bind("click", function(){
$("#SERVICE03_DLG").dialog("open");
$("#something").focus();
});
$("#SERVICE03_DLG").dialog({
autoOpen: false,
modal: true,
resizable: false,
title: "my title",
overlay: {
opacity: 0.5,
background: "black"
},
buttons: {
"OK": function() {
alert("hi!");
},
"cancel": function() {
$(this).dialog("close");
}
},
close: function(){
$("#something").val("");
}
});
}
}
$(document).ready(topMenu.init);
Here is the html that uses the flora theme:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>sample</title>
<script src="jquery-1.2.6.min.js" language="JavaScript"></script>
<link rel="stylesheet" href="flora/flora.all.css" type="text/css">
<script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script>
<script src="TopMenu.js" language="JavaScript"></script>
</head>
<body>
<input type="button" value="click me!" id="my_button">
<div id="SERVICE03_DLG" class="flora">please enter something<br><br>
<label for="something">somthing:</label> <input name="something" id="something" type="text" maxlength="20" size="24">
</div>
</body>
</html>
Here is the html that uses the downloaded themeroller theme:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>sample</title>
<script src="jquery-1.2.6.min.js" language="JavaScript"></script>
<link rel="stylesheet" href="jquery-ui-themeroller.css" type="text/css">
<script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script>
<script src="TopMenu.js" language="JavaScript"></script>
</head>
<body>
<input type="button" value="click me!" id="my_button">
<div id="SERVICE03_DLG" class="ui-dialog">please enter something<br><br>
<label for="something">somthing:</label> <input name="something" id="something" type="text" maxlength="20" size="24">
</div>
</body>
</html>
As you can see, only the referenced css file and class names are different.
Anybody have a clue as to what could be wrong?
#David: I tried it, and it doesn't seem to work (neither on FF or IE). I tried inline css:
style="z-index:5000"
and I've also tried it referencing an external css file:
#SERVICE03_DLG{z-index:5000;}
But neither of these work. Am I missing something in what you suggested?
Edit:
Solve by brostbeef!
Since I was originally using flora, I had mistakenly assumed that I have to specify a class attribute. Turns out, this is only true when you actually use the flora theme (as in the samples). If you use the customized theme, specifying a class attribute causes that strange behaviour.
I think it is because you have the classes different.
<div id="SERVICE03_DLG" class="flora"> (flora)
<div id="SERVICE03_DLG" class="ui-dialog"> (custom)
Even with the flora theme, you would still use the ui-dialog class to define it as a dialog.
I've done modals before and I've never even defined a class in the tag. jQueryUI should take care of that for you.
Try getting rid of the class attribute or using the "ui-dialog" class.
After playing with this in Firebug, if you add a z-index attribute greater than 1004 to your default div, id of "SERVICE03_DLG", then it will work. I'd give it something extremely high, like 5000, just to be sure.
I'm not sure what it is in the themeroller CSS that causes this. They've probably changed or neglected the position attribute of the target div that it turns into a dialog.
I tried implementing a themeroller theme with a dialog and tabs and it turns out that the themeroller CSS doesn't work with official jQuery! Especially for dialog and tabs, they modified the element classes from the official jquery ones. See here:
http://filamentgroup.com/lab/introducing_themeroller_design_download_custom_themes_for_jquery_ui/
A user's comment:
3) the generated theme that I
downloaded seems to be incomplete -
when I attempt to use it my tabs
(which work with the flora theme, code
identical to the documentation
example) do not get styled as tabs
Having run into 3 I thought I was
stuck and would have to revert using
“flora"… I have since discovered by
reading the source code of the “demo”
file that if I adjust my html and give
the < li> items I’m using for my tabs
the “ui-tabs-nav-item” class then it
will work.
The theme generated by themeroller is
thus unfortunately incomplete. If the
tabs stuff is incomplete, it makes me
wonder what else is incomplete. It
was rather frustrating. :(
followed by the themeroller developers comment:
3) We’ll take a look at that. You’re right that those classes
should be added by the plugin. For now though, it probably
wouldn’t hurt much to just add them to your markup so you
can use themeroller themes.
We’ll check it out, though. I think our selectors could be
based off of the parent ui-tabs selector instead, but I think
we were trying not to use elements in our selectors. Consider
it on the to-do list
Man, this is a good one. I've tried doing a bunch of things on these two pages. Have you tried just leaving the CSS out altogether and trying both pages then? I used Firebug to remove the CSS from the header on both pages, and the input still worked on one and not on the other - but, I'm inclined to believe that Firebug doesn't completely remove the CSS from the rendering, and you'll get different results if you actually remove it from the code.
I also found that you can paste text into the text box using the mouse - it just won't accept keyboard input. There doesn't seem to be any event handler on it that would interfere with this, though.

Categories

Resources