<div id="text">some开发者_Python百科 text</div>
<img src="#" onclick="$.function('http://url.com?q=some+text')"/>
I want the q=
to be dynamic using the text in the previous paragraph. I can get the text into a variable
var str = $("#text").text();
but am struggling to output this dynamically.
EDIT:
It's much simpler than I thought, figured out the solution from Darin's answer:
<div id="text"><p>Testing text to speech</p></div>
<div id="textlink"></div>
<img src="#" onclick="$.sound.play('http://translate.google.com/translate_tts?q='+ str)" />
<script>
var str = $("#text").text();
</script>
Just needed to know how to append a variable. Thanks
Lemme shoot in the dark:
<img src="#" onclick="window.location.href = 'http://url.com?q=' + encodeURIComponent($('#text').text());" />
or if you want to assign this src
dynamically:
<img src="#" id="foo"/>
and then:
$(function() {
$('#foo').click(function() {
window.location.href = 'http://url.com?q=' + encodeURIComponent($("#text").text());
});
});
Start of what I think you want to do:
$('img').click(function(){
var str = $("#text").text();
alert('http://url.com?q=' + str);
});
Or maayyyyybe:
$('img').click(function(){
var str = $("#text").text();
window.location = 'http://url.com?q=' + encodeURIComponent(str);
});
Or even:
$('img').click(function(){
var str = $("#text").text();
this.src = 'http://url.com?q=' + encodeURIComponent(str);
});
Fiddle: http://jsfiddle.net/maniator/UrDRX/
(works in HTML5 browsers, edit the color code)
And on and on....
Separation of concerns. In this case you want to keep behavior (javascript) separate from the content (html) and style (css). - http://en.wikipedia.org/wiki/Separation_of_concerns
So... onclick="x();"
is not preferred. Rather:
$(document).ready(function(
$("#buttonId").click(function() {
var val = $("#text").text();
var url = 'http://url.com?q=' + encodeURIComponent(val);
alert(url); // or window.location or whatever you want to accomplish
});
));
Perhaps, if you want to use the entire text-content of the paragraph:
var str = encodeURIComponent($('#text').text());
$('#linkId').attr('href','http://url.com?q=' + str);
JS Fiddle demo.
精彩评论