Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

html - Sending id via javascript listener

For all my other options this works great (i just editing the replace part to be the correct id)..

(Note: all "'s are 'd out as in production these are dynamically created with js)

<div class="singlecontrol"><span style="vertical-align: middle;">Colour Picker</span><input oninput="updatetxtcolour(event)" id="colourpicker"+textcount+"" value="#dfe481" type="color" autocomplete="off" ></div>
 
<script> 
function updatetxtcolour(e) {
    var ideditaded = e.target.getAttribute("id").replace("colourpicker", "");
document.getElementById("quotetext"+(ideditaded)).style.color = document.getElementById("colourpicker"+(ideditaded)).value;
}
 </script> 

But for my font picker it works like so...

<div class="singlecontrol"><span style="vertical-align: middle;">Font Picker</span><input id="font"+textcount+"" type="text" autocomplete="off" ></div>
 
 
<script> 
$('#font'+(textcount))
                .fontselect()
                .on('change', function() {
                applyFont(this.value);
                });
 
        } 
 
  
    function applyFont(font) {
      console.log('You selected font: ' + font);
     
      // Replace + signs with spaces for css
      font = font.replace(/+/g, ' ');
     
      // Split font into family and weight
      font = font.split(':');
     
      var fontFamily = font[0];
      var fontWeight = font[1] || 400;
     
      // Set selected font on paragraphs
      $('quotetext'+(textcount)).css({fontFamily:"'"+fontFamily+"'", fontWeight:fontWeight});
 
}
</script>

I'm having trouble getting the latter font picker to function in the same manner as the others, that is to pass the correct ID as these are created dynamically like so https://stackoverflow.com/a/69397361/4772471

All of my other options call a function oninput but this one uses a listener and then runs a function so i'm stumpted.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use (you must use the '#' sign):

$('#quotetext'+(textcount)).css({fontFamily:"'"+fontFamily+"'", fontWeight:fontWeight});

Instead of:

$('quotetext'+(textcount)).css({fontFamily:"'"+fontFamily+"'", fontWeight:fontWeight});

In addition, you can use template string (learn more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), will be much more readable:

$(`#quotetext${textcount}`)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...