开发者

Get this element Attribute and use it on other element

开发者 https://www.devze.com 2023-04-09 07:17 出处:网络
So... What I want is the following: When I .click an element with an id starting with \'menu\' it will get its attr value=\'开发者_如何学编程value\' into a variable and use it on the next function.

So... What I want is the following:

When I .click an element with an id starting with 'menu' it will get its attr value='开发者_如何学编程value' into a variable and use it on the next function.

Here's the source:

index.html

<div id='menuBar' >
  <img id='menu01' src='/si/img/menu.apresentacao.jpg' value='apresentacao' >
  <img id='menu02' src='/si/img/menu.servicos.jpg' value='servicos' >
</div>

jquery.js

$(document).ready(function() {

 $('img[id^='menu']').click( function(){

  var menuValue = $(this).attr('value');

  $('div#contentBox').fadeOut(300, function() {
   $('div#contentBox').replaceWith('<div id="contentBox">' + menuValue + '</div>');
  });
 });

});

variables.js

var servicos = "<p id='title'>Serviços</p><br><p id='text'>text text</p><br>";

Thanks in advance*


The only problem with your code is that your selector is malformed and therefor doesn't work:

$('img[id^='menu']').click( function(){
  ^        ^    ^ ^
  |        |    | |
  |        |    | \__ Closing single quote
  |        |    |
  |        |    \__ Opening single quote
  |        |
  |        |
  |        \__ Closing single quote
  |
  \__ Opening single quote


  ====> does not compute!

What it should be, is this (note the double quotes around "menu:):

$('img[id^="menu"]').click( function(){
           ^    ^
           |    |
           \    /
            \  /
             \/
              \_Double quotes, yay!

… and it works just fine: http://jsfiddle.net/HnsTu/


Instead of using var servicos use an object with the value of your image as a key.

var menuValueContent = {'servicos': '<p>....</p>', 'apre': '...'}; 

and in your click handler you can use menuValueContent[menuValue] to get the new content.

0

精彩评论

暂无评论...
验证码 换一张
取 消